Java

Type Casting and Type Conversion in Java

Type Casting and Type Conversion in Java convert a variable of a specific type to another type. However, there is a difference between typecasting and type conversion.

Type conversion always occurs automatically. The compiler performs it. As can be seen in the following example, type conversion may be successful or may not be.

Examples of Type Casting and Type Conversion in Java

class Conversions {
    public static void main(String[] args) {
        double d;
        int a=40, b;
        d=a;
        System.out.println("d = "+d); 
        //b=a*2.5;
    }
}

Output

d = 40.0

The following code shows a derived type object can be assigned to a base class reference variable. Since, base class reference variable is type compatible with the derived type object, it becomes possible.

Demonstrating Type Casting and Type Conversion in Java
Demonstrating Type Casting and Type Conversion in Java

When we assign the integer value to a double type variable, the compiler automatically converts its type to double. In contrast, the last statement in the code that sets a double type value to an integer variable results in error. Hence, the type conversion is used to convert a value of a narrower data type to a variable of a wider data type. However, the reverse is not true.

In order to perform typecasting, we need to use the typecasting operator (). The following code demonstrates the typecasting.

class Conversions {
    public static void main(String[] args) {
        double d=88.98996;
        int a=40, b=1566;
        byte t, t1;
        // Automatic type conversions will result in compile error
        // a=d;
        // t=a;
        //Typecasting
        t=(byte)a;
        a=(int)d;
        t1=(byte)b;
        System.out.println("a = "+a); 
        System.out.println("t = "+t); 
        System.out.println("t1 = "+t1); 
    }
}

Output

a = 88
t = 40
t1 = 30

Since here we assign the value of d (double type variable) to an integer variable, we need an explicit typecasting operator. However, the fractional part of the value assigned is truncated. Similarly, for assigning the value of integer type variables to the byte type variable, we need a typecasting operator. When the source value is bigger than what can be accommodated in the destination type variable, it is truncated and results in the wrong value being assigned. Therefore, when we assign the value of integer variable b to the byte variable t1, we get the incorrect result.

Since the programmers perform typecasting explicitly, it is more reliable and predictable. Also, typecasting is less error-prone. Whereas automatic type conversions are less reliable and can lead to incorrect results.

Another important difference between typecasting and type conversion is that type conversion occurs when the types are compatible.


Further Reading

Java Practice Exercise

programmingempire

You may also like...