Java Type Casting
Type Casting is nothing but to assign a value of one type to a variable of another type. If the two types are compatible, then Java will perform the conversion automatically. Java performs automatic type conversion if one of the following conditions are met:
PROGRAM
OUTPUT
- The two types are compatible.
- The destination type is larger than the source type.
(target-type) value
The following program demonstrate how to use type casting in Java.
PROGRAM
class TypeCasting {
public static void main(String[] args) {
byte b;
int val = 263;
double d = 9563.25;
long l = 56322145;
System.out.println("int val = "+val);
System.out.println("double d = "+d);
System.out.println("long l = "+l);
System.out.println("\nint to byte ");
b = (byte) val;
System.out.println(val+" to "+b);
System.out.println("\ndouble to int ");
System.out.println(d+" to "+(int)d);
System.out.println("\nlong to double ");
System.out.println(l+" to "+(double)l);
System.out.println("\nlong to short ");
System.out.println(l+" to "+(short)l);
System.out.println("\ndouble to byte ");
System.out.println(d+" to "+(byte)d);
}
}
The output is given below:
OUTPUT
C:\>javac TypeCasting.java C:\>java TypeCasting int val = 263 double d = 9563.25 long l = 56322145 int to byte 263 to 7 double to int 9563.25 to 9563 long to double 56322145 to 5.6322145E7 long to short 56322145 to 26721 double to byte 9563.25 to 91