Javaexercise.com

Java Type Casting

Type casting or type conversion involves conversion of one primitive type value to another primitive type either implicitly or explicitly. We can categories Java type conversion in two ways:

  1. Widening Primitive Conversion (Implicit)
  2. Conversion of narrow (smaller) data type value to wider (larger) data type is called widening primitive conversion which happens impicitly. For example byte can be converted to int type easily without lossing data.

    byte ---> short ---> int ---> long ---> float ---> double
  3. Narrowing Primitive Conversion (Explicit)
  4. Conversion of wider data type to narrower data type is called narrowing primitive conversion which requires explicitly type conversion. For example, converting float to int type will not convert implicitly and require some explicit casting.

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

Note: While doing explicit type casting, we may loss some amount of actual data.

Java Implicit Type Conversion Example

As we discussed above, Implicit type casting happens automatically by the Java compiler. In the below example, we are casting one smaller type to larger type easily and getting the same output without lossing actual data.

// Implicit type casting
public class Demo {
    public static void main(String[] args) {
        // Casting byte to int type
        byte a = 100;
        int b = a;
        System.out.println("value of a: "+a);
        System.out.println("value of b: "+b);
        // Casting int to long type
        long c = b;
        System.out.println("value of c: "+c);
        // Casting long to float type
        float d = c;
        System.out.println("value of d: "+d);
    }
}

Output:

value of a: 100
value of b: 100
value of c: 100
value of d: 100.0


Java Explicit Type Conversion Example

To deal with explicit type casting, Java mandates to perform casting by using the below programming syntax.

(<type>)<expression>

In the below example, we are using casting syntax to perform explicit type casting. Basically we are converting larger data type value to smaller data type.

// Explicit type casting
public class Demo {
    public static void main(String[] args) {
        // Casting float to long type
        float a = 100.25f;
        long b = (long)a; // It truncates result
        System.out.println("value of a: "+a);
        System.out.println("value of b:"+b);
        // Casting long to int type
        int c = (int)b;
        System.out.println("value of c:"+c);
        // Casting int to byte type
        byte d = (byte)c;
        System.out.println("value of d:"+d);
    }
}

Output:

value of a: 100.25
value of b: 100
value of c: 100
value of d: 100

See, when we cast float type value to long type then it truncates decimal point value. that's why we say always be careful while doing explicit type casting in your programs.