Explaining Java casting
To discuss casting properly, we need to explain both the widening and narrowing of Java’s primitive data types. With this in mind, it is helpful to remember the sizes of the primitive data types in bytes. Table 3.3 represents this information:
Table 3.3 – The sizes of Java’s primitive types
The preceding table presents the sizes in bytes of Java’s various primitive data types. This will help us as we discuss both widening and narrowing.
Widening
Widening is done automatically; in other words, a cast is not needed. As the promotion is done in the background, widening is also known as implicit promotion. With Table 3.3 in mind, the widening rules are as follows:
byte → short/char → int → long → float → double
Given the sizes from Table 3.3, most of these rules should make sense. For example, a byte
can automatically fit into a short
because 1 byte fits into...