Type casting is the process of converting a variable from one data type to another. Java is a strongly typed language, so type casting allows us to handle type mismatches in a controlled way.
There are two types of type casting in Java:
Widening Casting
Narrowing Casting
Widening Casting (Implicit)
This is done automatically when converting a smaller data type to a larger one. It's safe and doesn't lose any data.
Order:
byte → short → int → long → float → double
Example:
int i = 10;
double c = i; // Automatic casting: int to double
System.out.println(i); // Outputs 10
System.out.println(c); // Outputs 10.0
Narrowing Casting (Explicit)
This type of casting must be done manually. It converts a larger type to a smaller size type. This can lead to data loss or overflow.
Example:
double i = 9.78;
int c = (int) i; // Manual casting: double to int
System.out.println(i); // Outputs 9.78
System.out.println(c); // Outputs 9
Always be cautious with narrowing conversions — Java doesn’t throw a compile error, but you can lose precision.
reference link:
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
Top comments (0)