Primitive variable in Java – Part 2


In our previous tutorial, we looked at five of the eight primitive data types in Java. Now let’s look at the 3 remaining primitive data types.

float

The float is a 32-bit IEEE 754 binary floating-point type. It provides less precision than double and is useful when memory consumption is important and its precision is sufficient.

The declaration for a float variable is as follows:

double

double is a 64-bit IEEE 754 binary floating-point type. Compared with float, it generally provides greater precision and a wider range of values.

Example of declaring a double variable:



Some notes of float and double

– The default data type for decimals is double, and because floats cannot be automatically converted to double:

Primitive variable in Java - Part 2

so when declaring a variable as float, you must add the value of the variable F or f behind the variable.

Primitive variable in Java - Part 2

In addition, the double variable can also be added after the value of the letter D or d but redundant because it is already double by default.

– Since Java 7, we can also use the underscore in the declaration of the value of the variable as the data types byte, short, int, long. The principle of use is the same as byte, short, int, long but with the following additional note:

  • You cannot put the underscore before D, d, F or f.
  • You cannot put the underscore next to the decimal point in the float, double declaration.

– Java defines three special floating-point data types:

  • Double.POSITIVE_INFINITY
  • Double.NEGATIVE_INFINITY
  • Double.NaN

Double.POSITIVE_INFINITY is a positive infinity number, defined for the case where we divide a positive decimal number by 0.0. In this case, the result of the division will always be “Infinity”.

Double.NEGATIVE_INFINITY , on the other hand, is a negative infinity number, defined when we divide a negative decimal number by 0.0. The result will always be “-Infinity”.

Double.NaN , where NaN stands for Not a Number, defines the result for a calculation that is invalid for decimal numbers. For example, if you calculate 0.0 / 0.0, the result will be NaN.

boolean

A boolean variable can store one of two values true or false.

For example, declare a boolean variable as follows:

Add Comment