In Java, typecasting is a method or process that converts a data type into another data type in both ways manually and automatically.
- Automatically - byte -> short -> char -> int -> long -> float -> double
- Manually - double -> float -> long -> int -> char -> short -> byte
Automatically
it is also called Widening Casting converts smaller type to a larger type
JavaApplication .java
public class JavaApplication {
public static void main(String[] args) {
int myInt = 9;
double myDouble = myInt; // Automatic casting: int to double
System.out.println(myInt); // Outputs 9
System.out.println(myDouble); // Outputs 9.0
}
}
output:
9
9.0 |
Manually
It is also called Narrowing Casting convert larger type to a smaller
JavaApplication.java
public class JavaApplication {
public static void main(String[] args) {
int myInt = 9;
double myDouble = myInt; // Automatic casting: int to double
System.out.println(myInt); // Outputs 9
System.out.println(myDouble); // Outputs 9.0
}
}
Output:
9
9.0 |
Thanks, May this example help you.