✏️ Explanatory Question

What is type casting?

👁 648 Views
📘 Detailed Answer
💡

Answer with Explanation

What is Type Casting?

Type casting is the process of converting a variable from one data type to another. In Java, type casting is mainly classified into two types:

1. Implicit Type Casting (Widening Conversion)

  • Automatically performed by Java when converting a smaller data type to a larger one.
  • No data loss occurs during conversion.

Example:


public class Main {
    public static void main(String[] args) {
        int num = 100;
        double doubleNum = num; // Automatic widening conversion
        System.out.println(doubleNum); // Output: 100.0
    }
}

Conversion order: byte → short → int → long → float → double

2. Explicit Type Casting (Narrowing Conversion)

  • Manually performed by the programmer using (type).
  • Data loss may occur if the target type cannot hold the full value.

Example:


public class Main {
    public static void main(String[] args) {
        double num = 99.99;
        int intNum = (int) num; // Explicit casting (double to int)
        System.out.println(intNum); // Output: 99 (fractional part lost)
    }
}

Conversion order (narrowing): double → float → long → int → short → byte