Java Tutorial Series - Casting Numerical Values

In this article, we will learn about Casting numerical values. Casting is used to convert one data type to another.

Casting Numerical values - 

Before we begin, let's cover the size of data types or memories utilised by the data types -
int - 32 bit
short - 16 bit
byte - -128 to 127 ~256

Let's see an example below -

byte byteValue = 20;
short shortValue = 55;
int intValue = 888;
long longValue = 23355;

float floatValue = 8834.8f;
double doubleValue = 32.4;

System.out.println(Byte.MAX_VALUE); // prints 127

Converting data type long into int -
intValue =(int)longValue;
System.out.println(intValue);    //prints 23355

Converting double into int -
doubleValue = intValue;
System.out.println(doubleValue);    //prints 23355.0

Note- no need to cast it since we are not cutting off the value, only appending the value.

Converting float into int -
intValue = (int)floatValue;
System.out.println(intValue); // prints 8834

Note - It won't round off the value, to round off we have to use Math.round();

Converting int to byte -
byteValue = (byte)128;
System.out.println(byteValue); // prints -128

Converting intger to String -
Can be achieved using toString() method

Converting String to Integer -
Can be achieved using integer.parse(int)



Comments

Popular posts from this blog

Azure Tutorials Series - Azure Networking

Coforge Interview Questions | Automation Testing profile

Testing in CI/CD