Java Type Casting

Type casting is nothing but assiging a value of one primitive data type to another. For example short to integer and integer to short.

In java type casting are two different types:

1. Widening (automatically) - Widening casting is nothing but converting a smaller type to a larger type.

  1. byte -> short
  2. float -> double

2. Narrowing (manually) - Narrowing casting is nothing but converting a larger type to a smaller type.

  1. int -> short
  2. double -> float

Widening Casting example:

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

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