79. Using var with primitive types

The problem of using LVTI with primitive types (int, long, float, and double) is that the expected and inferred types may differ. Obviously, this causes confusion and unexpected behavior in code.

The guilty party in this situation is the implicit type casting used by the var type.

For example, let's consider the following two declarations that rely on explicit primitive types:

boolean valid = true; // this is of type boolean
char c = 'c'; // this is of type char

Now, let's replace the explicit primitive type with LVTI:

var valid = true; // inferred as boolean
var c = 'c'; // inferred as char

Nice! There are no problems so far! Now, let's have a look at another set of declarations based on explicit primitive types:

int intNumber = 10;       // this is of type int
long longNumber = 10; // this is of type long
float floatNumber = 10; // this is of type float, 10.0
double doubleNumber = 10; // this is of type double, 10.0

Let's follow the logic from the first example and replace the explicit primitive types with LVTI:

// Avoid
var intNumber = 10; // inferred as int
var longNumber = 10; // inferred as int
var floatNumber = 10; // inferred as int
var doubleNumber = 10; // inferred as int

Conforming to the following screenshot, all four variables have been inferred as integers:

The solution to this problem consists of using explicit Java literals:

// Prefer
var intNumber = 10; // inferred as int
var longNumber = 10L; // inferred as long
var floatNumber = 10F; // inferred as float, 10.0
var doubleNumber = 10D; // inferred as double, 10.0

Finally, let's consider the case of a number with decimals, as follows:

var floatNumber = 10.5; // inferred as double

The variable name suggests that 10.5 is float, but actually, it is inferred as double. So, it is advisable to rely on literals even for numbers with decimals (especially for numbers of the float type):

var floatNumber = 10.5F; // inferred as float
..................Content has been hidden....................

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