See the Tutorial List

Type Casting in Java

Assigning a value of one type to a variable of another type is known as Type Casting.

Example :

int x = 10;
byte y = (byte)x;

In Java, type casting is classified into two types,

  • Widening Casting(Implicit)
  • widening-type-conversion

  • Narrowing Casting(Explicitly done)
  • narrowing-type-conversion


Widening or Automatic type converion

Automatic Type casting take place when,

  • the two types are compatible
  • the target type is larger than the source type

Example:

public class Test
{
    public static void main(String[] args)
    {
      int i = 100;
      long l = i;	//no explicit type casting required
      float f = l;	//no explicit type casting required
      System.out.println("Int value "+i);
      System.out.println("Long value "+l);
      System.out.println("Float value "+f);
    }

}

Int value 100 Long value 100 Float value 100.0


Narrowing or Explicit type conversion

When you are assigning a larger type value to a variable of smaller type, then you need to perform explicit type casting.

Example :

public class Test
{
    public static void main(String[] args)
    {
      double d = 100.04;
      long l = (long)d;  //explicit type casting required
      int i = (int)l;	//explicit type casting required

      System.out.println("Double value "+d);
      System.out.println("Long value "+l);
      System.out.println("Int value "+i);
    }

}

Double value 100.04 Long value 100 Int value 100

Example of Explicit Conversion

  
class CastingDemo1
{ 
    public static void main(String[] args) 
    { 
        double d = 120.04;  
        long l = (long)d;   
inti = (int)l;  
System.out.println("Double value "+d); 
System.out.println("Long value "+l);  
System.out.println("Int value "+i);  
    }  
}
  

casting-demo Image

Example for Conversion of int and double into a byte

  
class Demo2
{ 
    public static void main(String args[])  
    {  
        byte b;  
inti = 355;  
        double d = 423.150; 
  b = (byte) i; 
System.out.println("Conversion of int to byte: i = " + i + " b = " + b);  
System.out.println("*************************************************"); 
  b = (byte) d;        
  System.out.println("Conversion of double to byte: d = " + d + " b= " + b);
  } 
}
  

Output of conversion-example