Java Type Casting

In Java, type casting is the process of converting a data from one datatype to another datatype. This can be done manually or automatically.

In java there are 2 types of casting

  • Widening Casting - This is done automatically by the compiler. The compiler converting a smaller type to a larger size type.
    byte -> short -> char -> int -> long -> float -> double

  • Narrowing Casting - This is done manually by converting a larger type to a smaller size type
    double -> float -> long -> int -> char -> short -> byte

Widening Type Casting

Widening type casting refers to the transformation of a lower data type into a higher one. Casting down and implicit conversion are other names for it.

Example

public class Main {
  public static void main(String[] args) {
    int number= 10;
    // Automatically converts int to double
    double doubleNumber = number;
    // Automatically converts int to float
	float floatNumber = number; 
	System.out.println(number);
    System.out.println(doubleNumber);
    System.out.println(floatNumber); 
  }
}

Output

10
10.0
10.0

Here, the int variable is assigned to double and float variable. So the int is smaller datatype so it is automatically converted to double and float.

Narrowing Type Casting

Narrowing type casting refers to the transformation of a higher data type into a lower one. The programmer has to do specify type casting manually. Compile-Time error is reported by the compiler if casting is not done.

Example

public class Main 
{
  
public static void main (String args[]) 
  {
    
	double d = 143.45;
	     
	//converting double data type to long datatype  
	    long l = (long) d;
	     
	//converting long datatype to int datatype  
	    int i = (int) l;
	     
	System.out.println ("Double: " + d);
	     
	//fractional part lost  
	      System.out.println ("Long type: " + l);
	     
	//fractional part lost  
	      System.out.println ("Int type: " + i);
	 
	} 
}

Output

Double: 143.45
Long type: 143
Int type: 143

Here, we are trying to type cast double to long and int data type which is smaller type than double so explicit type casting is necessary.


Most Read