What is the difference between a widening and a narrowing cast in Java, and which one does the compiler perform for you?
There are two kinds of conversion, and they differ in one important way. A widening conversion moves a value into a type that can hold every value of the original type, so nothing is lost. A narrowing conversion goes the other way, and it can throw information away.
The compiler does the widening conversions for you, without you asking. The order runs from byte to short to int to long to float to double. A char widens to int and then onwards, and an int widens to a float or a double as well. Widening is always safe, and that is exactly why the language allows it without a cast. It also explains why the opposite direction needs a cast. A long cannot be given to an int without help, because an int cannot hold every long.
A narrowing conversion needs an explicit cast, which tells the compiler that you really meant to lose something. Narrowing from a type with a fraction down to a whole number cuts the fraction off towards zero, so 19.99 becomes 19. Narrowing from a wide whole number down to a narrow one throws away the high bits and keeps only the low ones, which behaves like taking a remainder rather than like stopping at a limit.
public class Main {
public static void main(String[] args) {
int small = 42;
long wide = small; // widening: done for you, and nothing is lost
double bigger = small; // widening again, and still nothing is lost
long big = 300L;
int narrowed = (int) big; // narrowing: the cast is required
double price = 19.99;
int whole = (int) price; // 19, because the fraction is cut off
System.out.println("wide : " + wide);
System.out.println("bigger : " + bigger);
System.out.println("narrowed: " + narrowed);
System.out.println("whole : " + whole);
}
}
The next question in this topic looks at how to narrow a big number without quietly ruining it.