Type Casting In Java

java

Type casting is when you want to assign value of one data type to another data type. There are two types of casting.

  • Widening Casting: This can be done automatically.
  • Narrowing Casting: This can be done manually.

Widening casting

Widening casting is done automatically when you passes smaller size type to larger size type.

byte -> short -> char -> int -> long -> float -> double

Example
public class MyClass {
  public static void main(String args[]) {
    int intVar= 7;
    double doubleVar= intVar; // Widening casting: int to double

    System.out.println(intVar);      // Outputs 7
    System.out.println(doubleVar);   // Outputs 7.0
  }
}

Narrowing Casting

Narrowing casting must be done manually by using type parentheses as shown in below code snippet.

public class MyClass {
  public static void main(String args[]) {
    double doubleVar= 11.6;
    int intVar= (int) doubleVar; // Narrowing casting: double to int

    System.out.println(doubleVar);   // Outputs 11.6
    System.out.println(intVar);      // Outputs 11
  }
}

Leave a Comment

Your email address will not be published. Required fields are marked *