Explain Type Casting in Java with Example

Type Casting in Java

Type casting in Java is the process of converting a variable from one data type to another. It can be divided into two types:

  • Implicit Type Casting in Java(Widening Conversion): Automatically done by the Java compiler when converting a smaller data type to a larger data type.
  • Explicit Type Casting in Java (Narrowing Conversion): Requires explicit conversion by the programmer when converting a larger data type to a smaller data type.

Implicit Type Casting in Java(Widening Conversion)

Implicit casting happens when you assign a value of a smaller data type to a larger data type. This is done automatically by the compiler and does not require any special syntax.

Example:

public class ImplicitCastingExample {
    public static void main(String[] args) {
        int myInt = 9;
        double myDouble = myInt; // Automatic casting: int to double

        System.out.println("Integer value: " + myInt);   // Outputs 9
        System.out.println("Double value: " + myDouble); // Outputs 9.0
    }
}

In this example, the integer myInt is automatically cast to a double when assigned to myDouble.

Explicit Type Casting in Java (Narrowing Conversion)

Explicit casting is necessary when you are converting a larger data type to a smaller data type. This requires you to specify the target data type in parentheses before the value being cast.

Example:

public class ExplicitCastingExample {
    public static void main(String[] args) {
        double myDouble = 9.78;
        int myInt = (int) myDouble; // Manual casting: double to int

        System.out.println("Double value: " + myDouble); // Outputs 9.78
        System.out.println("Integer value: " + myInt);   // Outputs 9
    }
}

In this example, the double myDouble is explicitly cast to an integer using (int) before the variable myDouble. This truncates the decimal part and assigns the integer part to myInt.

Summary

  • Implicit Type Casting in Java: Automatically done by the compiler, e.g., int to double.
  • Explicit Type Casting in Java: Must be done manually by the programmer, e.g., double to int.

Understanding type casting is crucial for handling data conversion between different types and ensuring that your program handles values correctly

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

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