Java – Type Casting

Type casting is a way of converting one data type’s value to another data type’s value. Type conversion is another name for it. There are numerous types of conversions in Java. However, we will only cover two important categories in this lesson.

  • Widening Type Casting
  • Narrowing Type Casting

Visit this page to learn more about additional Java conversions.

 

Widening Type Casting

When converting smaller data types to bigger data types, the widening type casting (widening conversion) occurs automatically. The compiler typecasts smaller data types to bigger data types implicitly. There will be no data loss as a result of this procedure.

Example

The widening conversion is demonstrated in Java in the example below.

public class MyClass {
  public static void main(String[] args) {      
    byte num_byte = 10;

    //Widening Casting
    short num_short = num_byte;
    int num_int = num_short;
    long num_long = num_int;
    float num_float = num_long;
    double num_double = num_float;

    //printing variables
    System.out.println("num_byte = " + num_byte); 
    System.out.println("num_short = " + num_short);
    System.out.println("num_int = " + num_int);
    System.out.println("num_long = " + num_long);
    System.out.println("num_float = " + num_float); 
    System.out.println("num_double = " + num_double); 
  }
}

The output of the above code will be:

num_byte = 10
num_short = 10
num_int = 10
num_long = 10
num_float = 10.0
num_double = 10.0

Narrowing Type Casting

Narrowing type casting (narrowing conversion) is not a natural process. It’s done manually by explicitly invoking the compiler to typecast the bigger data types into smaller data types. This approach may result in data loss.

Java Type Casting

Example

The example below demonstrates how to accomplish narrowing conversion by explicitly invoking the compiler.

public class MyClass {
  public static void main(String[] args) {    
    double num_double = 10.5d;

    //Narrowing Casting
    float num_float = (float) num_double;
    long num_long = (long) num_float;
    int num_int = (int) num_long;
    short num_short = (short) num_int;
    byte num_byte = (byte) num_short;

    //printing variables
    System.out.println("num_double = " + num_double);
    System.out.println("num_float = " + num_float); 
    System.out.println("num_long = " + num_long);
    System.out.println("num_int = " + num_int);  
    System.out.println("num_short = " + num_short);
    System.out.println("num_byte = " + num_byte);
  }
}

The output of the above code will be:

num_double = 10.5
num_float = 10.5
num_long = 10
num_int = 10
num_short = 10
num_byte = 10

Click here to use the online java Complier.

Next: Java Operators

Leave a Reply

Your email address will not be published.