Facebook Page Twitter Page LinkedIn Page
× Java Tutorial Java Advanced Java Resources


The type casting is a method of converting the value of one data type to another data type. It is also known as type conversion. In Java, there are several kinds of conversions. However, in this tutorial we will focus only on two major types.

  • Widening Type Casting
  • Narrowing Type Casting

To learn more about other types of conversion in Java, please visit Conversions and Contexts (official Java documentation).

Widening Type Casting

The widening type casting (widening conversion) happens automatically when converting a smaller data types to larger data types. The compiler implicitly typecast the smaller data types to the larger data types.

Java Widening Casting

Example

The below example shows how the widening conversion is done in Java.

public class MyClass {
  public static void main(String[] args) {      
    byte i = 10;

    //Widening Casting
    short j = i;
    int k = j;
    long l = k;
    float m = l;
    double n = m;

    //printing variables
    System.out.println("i is a byte. i = " + i); 
    System.out.println("j is a short. j = " + j);
    System.out.println("k is an int. k = " + k);
    System.out.println("l is a long. l = " + l);
    System.out.println("m is a float. m = " + m); 
    System.out.println("n is a double. n = " + n); 
  }
}

The output of the above code will be:

i is a byte. i = 10
j is a short. j = 10
k is an int. k = 10
l is a long. l = 10
m is a float. m = 10.0
n is a double. n = 10.0

Narrowing Type Casting

The narrowing type casting (narrowing conversion) does not happen automatically. It is performed manually by calling the compiler explicitly to typecast the larger data types into the smaller data types.

Java Narrowing Casting

Example

The below example shows how the perform narrowing conversion by calling the compiler explicitly.

public class MyClass {
  public static void main(String[] args) {    
    double i = 10.5d;

    //Narrowing Casting
    float j = (float) i;
    long k = (long) j;
    int l = (int) k;
    short m = (short) l;
    byte n = (byte) m;

    //printing variables
    System.out.println("i is a double. i = " + i);
    System.out.println("j is a float. j = " + j); 
    System.out.println("k is a long. k = " + k);
    System.out.println("l is an int. l = " + l);  
    System.out.println("m is a short. m = " + m);
    System.out.println("n is a byte. n = " + n);
  }
}

The output of the above code will be:

i is a double. i = 10.5
j is a float. j = 10.5
k is a long. k = 10
l is an int. l = 10
m is a short. m = 10
n is a byte. n = 10