Java Type Casting

18-Sep-2024

Learn how to convert one data type into another in Java using type casting.


In programming, we often need to convert one data type to another. This conversion process is type casting.


In Java, there are two types of type casting:

  1. Widening Casting (Implicit)

  2. Narrowing Casting (Explicit)


Widening Casting ( Automatic ) 

 

Widening casting occurs when we convert a smaller data type to a larger one. For example, int data type converts to double. This type of casting happens automatically. It is also known as Implicit casting




int myInt = 9;
double myDouble = myInt; // Automatic casting: int to double

System.out.println(myInt) // Outputs 9
System.out.println(myDouble) // Outputs 9.0


In this example, the integer myInt is automatically converted to a double myDouble. This is safe because a double wider range than and int.



Narrowing Casting ( Manually )

  Narrowing casting occurs when we convert a larger data type to a smaller one. For example, double data type converts to int. This type of casting must be done manually by placing the target data type in parentheses before the variable. It is also known as Explicit casting

 



double myDouble = 9.78d;
int myInt = (int) myDouble; // Manual casting: double to int

System.out.println(myDouble); // Outputs 9.78
System.out.println(myInt); // Outputs 9


In this example, myDouble is explicitly cast to an int myInt. This conversion may lead to data loss, as shown where 9.78 becomes 9.

Comments