If you need to convert value in a larger capacity data type in to a smaller capacity data type, then you need a casting.
Ex: (long variables capacity: 8 bits, and integer variables capacity 4 bits. Casing the value in long into integer)
Int myInteger = (int)myLong;
Casing can be used to conversions of two different data types with similar capacity.
Ex: (integers are 4 bits and floats are 4 bits too. Casing the value in integer into float)
Float myfloat = (float)myInteger;
Sample Program:
Case: We will define 3 variables and we will cast them.
public class Casting
{
public static void main(String[] args)
{
int myInteger = 64; //integers are 4bytes
float myFloat = 0; //floats are 4bytes
byte myByte = 0; // bytes are 1 byte
System.out.println("Casting similar capacity variables...");
myFloat = (float)myInteger;
System.out.println(myFloat);
System.out.println("Casing larger variable value into samller...");
myByte = (byte)myInteger;
System.out.println(myByte);
}
}
This is the output:
No comments:
Post a Comment