Type casting is nothing but assiging a value of one primitive data type to another. For example short to integer and integer to short.
In java type casting are two different types:
1. Widening (automatically) - Widening casting is nothing but converting a smaller type to a larger type.
2. Narrowing (manually) - Narrowing casting is nothing but converting a larger type to a smaller type.
public class Main {
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
}
}
public class Main {
public static void main(String[] args) {
double myDouble = 9.78d;
int myInt = (int) myDouble; // Manual casting: double to int
System.out.println(myDouble); // Outputs 9.78
System.out.println(myInt); // Outputs 9
}
}