Java Type Casting

Java Type Casting

Type casting is when you assign a value of one primitive data type to another type. In Java, there are two types of casting:

  1. Widening Casting (Implicit/Automatic): Converting a smaller type to a larger type size.
  2. Narrowing Casting (Explicit/Manual): Converting a larger type to a smaller size type.

1. Widening Casting

Widening casting is done automatically when passing a smaller size type to a larger size type. This is considered safe as there is no risk of data loss.

The order is: byte -> short -> char -> int -> long -> float -> double

Widening Casting Example

public class Main {
  public static void main(String[] args) {
    int myInt = 9;
    // Automatic casting: int to double
    double myDouble = myInt; 
    System.out.println(myInt);      // Outputs 9
    System.out.println(myDouble);   // Outputs 9.0
  }
}

2. Narrowing Casting

Narrowing casting must be done manually by placing the desired type in parentheses () in front of the value. This is potentially unsafe because you might lose information.

The order is: double -> float -> long -> int -> char -> short -> byte

Narrowing Casting Example

public class Main {
  public static void main(String[] args) {
    double myDouble = 9.78d;
    // Manual casting: double to int
    int myInt = (int) myDouble; 
    System.out.println(myDouble);   // Outputs 9.78
    System.out.println(myInt);      // Outputs 9 (the fractional part is lost)
  }
}

When you cast the double value 9.78 to an int, the decimal part is truncated (cut off), resulting in the integer 9. This is an example of data loss.