Type Casting¶
Type casting is process of assigning a value of one data type to another data type. There are two types of casts in Java, Widening and Narrowing.
Widening Casting¶
Widening casts are done automatically. A widening cast only happens when going from a smaller data type to a larger data type. The list from smallest to largest is listed below.
byte
short
char
int
long
float
double
Note
The data type boolean cannot be type casted.
Examples¶
int
-> long
1 2 3 4 5 | int typeInt = 42; long typeLong = typeInt; System.out.println(typeInt); System.out.println(typeLong); |
Output
42
42
byte
-> double
1 2 3 4 5 | byte typeByte = 2; double typeDouble = typeByte; System.out.println(typeByte); System.out.println(typeDouble); |
Output
2
2.0
Narrowing Casting¶
Narrowing casting is done when a larger data type needs to be converted to a smaller data type.
Examples
float
-> short
1 2 3 4 5 | float typeFloat = -42.27; short typeShort = (short) typeFloat; System.out.println(typeFloat); System.out.println(typeShort); |
Output
-42.27
-42