Typecasting is used to temporarily change the data type of a value. There are two types of data in Java:
Java supports widening casting and narrowing casting.
Widening casting changes a smaller data type to a larger data type. For example, byte
→ short
→ char
→ int
→ long
→ float
→ double
.
This type of casting is usually automatic; you do not need to use
()
.
Narrowing casting changes the data type from a larger data type to a smaller data type. For example, double
→ float
→ long
→ int
→ char
→ short
→ byte
.
class myClass {public static void main( String args[] ) {int number = 7;double doubleNumber = number; // Widening casting: int to doubleSystem.out.println(number); // 7System.out.println(doubleNumber); // 7.0}}
class myClass {public static void main( String args[] ) {double number = 7.3;int intNumber = (int) number; // Narrowing casting: int to doubleSystem.out.println(number); // 7.3System.out.println(intNumber); // 7}}
Free Resources