What is Typecasting?
Typecasting refers to the process of converting a variable of one data type
into another.
There are two types of typecasting in Java
1. Implicit typecasting: This type of conversion occurs when you are converting a smaller data type to a larger data type.
Note: Implicit typecasting automatically perform by the java compiler.
Example
class ImplicitConversion {
public static void main(String[] args) {
int num = 10;
double numDouble = num; // Implicit casting (widening) from int to double
System.out.println("Integer: " + num);
System.out.println("Double: " + numDouble);
}
}
Output:
Integer: 10
Double: 10.0
2. Explicit typecasting: This conversion involves converting a larger data type to a smaller data type.
Note: As this may result in data loss.
Example
class ExplicitConversion {
public static void main(String[] args) {
double numDouble = 10.5;
int num = (int) numDouble; // Explicit casting (narrowing) from double to int
System.out.println("Double: " + numDouble);
System.out.println("Integer: " + num);
}
}
Output:
Double: 10.5
Integer: 10