Type casting is where you can convert a variable’s numeric data type into another one. This is really handy if you want a variable to be more precise/less precise. There are two types of type casting in Java: widening casting and narrowing casting.
Widening casting is where you want to convert from a smaller numeric data type to a larger data type. Fortunately, this is automatically done by Java, so you don’t have to do anything here. But, it is still important to understand the logic.
byte → short → char → int → long → float → double
Here’s an example:
public class MyClass {
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.printlin(myDouble); //*Outputs 9.0*
}
}
Source: w3schools.com
Narrowing Casting is pretty much the opposite of widening casting in that you use it when you want to convert a larger data type into a smaller one. This is not automatically done by Java, so you have to manually do it.
double → float → long → int → char → short → byte
To narrow cast, you put the data type that you want to cast the variable into in a pair of parentheses. For example, if I have a variable of type double and I want to convert it into an int
, then I would put int
in front of the variable. Here’s an example: