Java Type Casting

The Primitive datatypes in Java are the following: byte, short, int, long, float, double, boolean, and char. Type Casting is to convert one data type to another. There are two types of Type Casting in Java:

  • Automatic Type Casting
  • Manual Type Casting

Automatic/ Widening Type Casting in Java

The Widening type casting is handled by Java on its own i.e., it occurs when you want to convert a smaller type to a larger type.

The flow for Widening type casting in Java includes:

Widening Typecasting in Java

 

Let us see an example of the Automatic/ Widening Type Casting in Java:

class Studyopedia {

  public static void main(String[] args) {
    
    // int type
    int a = 25;  
    
    // int to float type i.e. Automatic/ Widening Type Casting
    float b = a;  
    
    System.out.println("The int = "+a);  
    System.out.println("After Automatic Casting, the float value = "+b);  
  }
}

Output

The int = 25
After Automatic Casting, the float value = 25.0

Manual/ Narrowing Type Casting in Java

The narrowing type casting is handled by Java on its own i.e., it occurs when you want to convert a larger type to a smaller type.

The flow for Automatic type casting in Java includes:

Narrowing Typecasting in Java

Let us see an example of the Manual/ Narrowing Type Casting in Java:

class Studyopedia {

  public static void main(String[] args) {
    
    // float type
    float a = 25.7f;  
    
    // float to int type i.e. Manual/ Narrow Type Casting
    int b = (int)a;  
    
    System.out.println("The float = "+a);  
    System.out.println("After Manual Casting, the int value = "+b);  
  }
}

Output

The float = 25.7
After Manual Casting, the int value = 25


If you liked the tutorial, spread the word and share the link and our website Studyopedia with others.


For Videos, Join Our YouTube Channel: Join Now


Read More

Java Comments
Java Threading
Studyopedia Editorial Staff
[email protected]

We work to create programming tutorials for all.

No Comments

Post A Comment