Java Type Casting

Type casting in Java is the process of converting one data type into another. This is commonly used in scenarios where you need to handle data of different types, or to explicitly instruct the compiler to convert a value.

There are two main types of casting in Java:

1. Widening (Automatic) Casting

Also known as implicit casting, this occurs automatically when a smaller data type is converted into a larger data type.

Order of Data Types (Widening Path)

byte → short → int → long → float → double

Example:


public class TypeCastingExample {
    public static void main(String[] args) {
        int num = 10;         // Integer value
        double result = num;  // Automatic casting to double
        System.out.println("Integer value: " + num);
        System.out.println("Widened to double: " + result);
    }
}

Output:

Integer value: 10 Widened to double: 10.0

2. Narrowing (Explicit) Casting

Also known as manual casting, this requires explicit instruction because data loss is possible when converting a larger type to a smaller type.

Order of Data Types (Narrowing Path)

double → float → long → int → short → byte

Example:


public class TypeCastingExample {
    public static void main(String[] args) {
        double decimalNumber = 12.25;  // Double value
        int wholeNumber = (int) decimalNumber;  // Manual casting to int
        System.out.println("Double value: " + decimalNumber);
        System.out.println("Narrowed to int: " + wholeNumber);
    }
}

Output:

Double value: 12.25 Narrowed to int: 12