Learn Java

Learn Java Type Casting

Java Type Casting is the process of converting a value from one data type to another data type. Type casting is also known as type conversion or data type conversion.

In Java, there are two types of type casting: implicit type casting (also known as widening conversion) and explicit type casting (also known as narrowing conversion).

 

  1. Implicit Type Casting (Widening Conversion):

Implicit type casting is the conversion of a data type to a larger data type. In this type of casting, the compiler automatically converts the smaller data type to the larger data type. This type of casting does not result in any data loss.

Example:

int a = 10;
double b = a;

In the above example, the integer variable a is implicitly typecast to a double variable b.

 

For example:

public class first {


    public static void main(String[] args) {


        int i = 100;
        long l = i;
        // Implicit Type Casting
        float f = l;
        // Implicit Type Casting
        System.out.println("i = " + i);
        System.out.println("l = " + l);
        System.out.println("f = " + f);


    }
}

Java Type Casting

 

Output:

i = 100
l = 100
f = 100.0

 

In the above example, we have assigned an integer value to an int variable i, then we assigned i to a long variable l, and then we assigned l to a float variable f. Since long and float are larger data types than int, Java automatically performs implicit type casting.

 

 

  1. Explicit Type Casting (Narrowing Conversion):

Explicit type casting is the conversion of a data type to a smaller data type. In this type of casting, the programmer manually converts the larger data type to the smaller data type. This type of casting may result in data loss.

Example:

double a = 10.5;
int b = (int) a;

 

For example:

double d = 1234.56;
long l = (long) d; //Explicit Type Casting
int i = (int) l; //Explicit Type Casting
System.out.println("d = " + d);
System.out.println("l = " + l);
System.out.println("i = " + i);

 

public class first {


    public static void main(String[] args) {


        double d = 1234.56;
        long l = (long) d; // Explicit Type Casting
        int i = (int) l; // Explicit Type Casting


        System.out.println("d = " + d);
        System.out.println("l = " + l);
        System.out.println("i = " + i);


    }
}

Java Type Casting explict

Output:

d = 1234.56
l = 1234
i = 1234

 

In the above example, we have assigned a double value to a double variable d, then we assigned d to a long variable l using Explicit Type Casting, and then we assigned l to an int variable i using Explicit Type Casting. Since int is a smaller data type than long and double, we need to explicitly cast the value to an int.

Note: While performing Explicit Type Casting, we need to be careful because it may cause data loss or truncation if the value being cast is larger than the target data type can handle.