17 Jan 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:
Let us see an example of the Automatic/ Widening Type Casting in Java:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
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
1 2 3 4 |
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:
Let us see an example of the Manual/ Narrowing Type Casting in Java:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
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
1 2 3 4 |
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
No Comments