Java Type Casting

We are discussing Java type casting with examples, in order to meet learners’ needs.

Java type casting

Java Type Casting

When a value of one primitive data type is assigned to another primitive data type, it is called type casting.

There are two types of casting in Java:

  • Widening Casting (automatically) – converting a smaller size data type to a larger size. (Byte -> short -> char -> int -> long -> float -> double)
  • Narrowing Casting (manually) – converting a larger size data type to a smaller size. (Double -> float -> long -> int -> char -> short -> byte)


Widening Casting

Widening casting is done automatically when passing a small size to a large size:

Example: 

public class Main { public static void main(String[] args) { int my_Int_value = 20; double my_Double = my_Int_value; // Automatic casting: int to double System.out.println(my_Int_value); System.out.println(my_Double); } }

Example: 

public class Main { public static void main(String[] args) { int my_Int_ample = 17; long my_long_mrx = my_Int_ample; // Widening casting is applied here which converts int to longSystem.out.println("Integer value: "+my_Int_ample); System.out.println("Long value: "+my_long_mrx); } }

 


Narrowing Casting

Narrowing casting is done manually by placing the type in parentheses before the value:

Example: 

public class Main { public static void main(String[] args) { double my_Double_value = 126.7d; byte my_Byte_value = (byte) my_Double_value; // Explicit casting: double to byte System.out.println("Actual Double Value : "+my_Double_value); System.out.println("After Narrowing casting modified value is: "+my_Byte_value); } }

Similarly, we can also convert the double(8 byte) value to float(4 byte):

Example: 

public class Main { public static void main(String[] args) { double my_Double_value = 437.7241d; float my_float_value = (float) my_Double_value; // Explicit casting: double to floatSystem.out.println("Actual Double Value : "+my_Double_value); System.out.println("After Narrowing casting float value is: "+my_float_value); } }
We value your feedback.
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0

Subscribe To Our Newsletter
Enter your email to receive a weekly round-up of our best posts. Learn more!
icon

Leave a Reply

Your email address will not be published. Required fields are marked *