81. Explicit downcast or better avoid var

In the Using var with primitive types section, we talked about using literals with primitive types (int, long, float, and double) to avoid issues caused by implicit type casting. But not all Java primitive types can take advantage of literals. In such a situation, the best approach is to avoid using var. But let's see why!

Check out the following declarations of byte and short variables:

byte byteNumber = 25;     // this is of type byte
short shortNumber = 1463; // this is of type short

If we replace the explicit types with var, then the inferred type will be int:

var byteNumber = 25;    // inferred as int
var shortNumber = 1463; // inferred as int

Unfortunately, there are no literals available for these two primitive types. The only approach to help the compiler to infer the correct types is to rely on an explicit downcast:

var byteNumber = (byte) 25;     // inferred as byte
var shortNumber = (short) 1463; // inferred as short

While this code compiles successfully and works as expected, we cannot say that using var brought any value compared to using explicit types. So, in this case, it is better to avoid var and explicit downcast.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.216.47.169