Type Casting in Java | technical-arbaab

what is Type casting in java

Let's see what is type casting and how it is implemented in java type casting is simply to assign a value of one primitive data type to another and there are two types of type casting 
which are come into consideration-

  • Widening type casting ( Automatic type casting )
  • Narrowing type casting ( Manual type casting )

1. Widening type casting(automatic typecasting): It is also known as automatic type casting or implicit type conversion in which you can convert a byte type into a short or a short type into a charchar type into a int, int type into a long, long type into a float, float type into a double and it doesn't mean you cannot convert short into a float or a int into a double, you can also do this have a look on this picture of automatic type casting to get a clear idea of it-



but you cannot follow it's reverse order like long into a int or  float into a byte or double into a int and similarly others this will comes under narrowing type casting and one point to clear you is that you must be wondering about boolean data type so you cannot type cast a boolean data type simply let's see how it is done actually in a code-

 public class WideningTypeCasting {  
      public static void main(String[] args)  
      {  
           byte x1 = 2;  
           int x2 = x1;//automatic type casting  
           System.out.println("the value of x2 is "+x2+"\n");  
           float x3 = 43.67f;  
           double x4 = x3;//automatic type casting  
           System.out.println("the value of x4 is "+x4+"\n");  
      }  
 }  

Output:

 the value of x2 is 2  
 the value of x4 is 43.66999816894531  

2.Narrowing type casting(manual typecasting): It is also known as manual type casting or explicit type conversion, it is just opposite of automatic type casting like if you want to type cast the data types shown in above picture in reverse order like double to float, float to long or long to int then you have to do this manually have a look on this picture of manual  type casting to get a clear idea of it-




let's see how it is done actually in a code-

 public class NarrowingTypeCasting {  
      public static void main(String[] args)  
      {  
           long x1 = 434343434343l;  
           int x2 = (int) x1;//manual typecasting  
           System.out.println("the value of x2 is "+x2+"\n");  
           float x3 = 54.56f;  
           byte x4 = (byte)x3;  
           System.out.println("the value of x4 is "+x4);  
      }  
 }  

Output:

 the value of x2 is 551737447  
 the value of x4 is 54  
















 







   



Comments