Java Reference
In-Depth Information
The value of all integral types ( int , long , byte , short , and char ) can be assigned to a variable of the float data
type without using an explicit cast. The following are some examples of using the float data type:
int num1 = 15000;
float salary = num1; // Ok. int variable to float
salary = 12455; // Ok. int literal to float
float bigNum = Float.MAX_VALUE; // Assigns maximum float value
bigNum = 1226L; // Ok, a long literal to float
float justAChar = 'A'; // Ok. Assigns 65.0F to justAChar
// Ok. Assigns positive infinity to the fInf variable
float fInf = Float.POSITIVE_INFINITY;
// Ok. Assigns Not-a-Number to fNan variable
float fNan = Float.NaN;
// A compile-time error. Cannot assign a float literal to a float variable
// greater than the maximum value of float(3.4E38F approx)
float fTooBig = 3.5E38F;
// A compile-time error. Cannot assign a float literal to a float variable less
// than the minimum value (greater than zero) of float 1.4E-45F
float fTooSmall = 1.4E-46F;
A float value must be cast before it is assigned to a variable of any integral data type int , long , byte , short , or char .
int num1 = 10;
float salary = 10.0F;
num1 = salary; // An error. Cannot assign float to int
num1 = (int)salary; // Ok
Most floating-point numbers are approximation of their corresponding real numbers. The assignment of int and
long to float may result in loss of precision. Consider the following piece of code:
int num1 = 1029989998; // Stores an integer in num1
float num2 = num1; // Assigns the value stored in num1 to num2
int num3 = (int)num2; // Assigns the value stored in num2 to num3
You expect that the value stored in num1 and num3 should be same. However, they are not the same because the
value stored in num1 cannot be stored exactly in a floating-point format in the float variable num2 . Not all floating-point
numbers have an exact representation in binary format. This is the reason that num1 and num3 are not equal.
Please refer to the section “Binary Representation of Floating-Point Numbers” for more details.
The double Data Type
The double data type uses 64 bits to store a floating-point number in the IEEE 754 standard format. A floating-point
number represented in 64 bits according to IEEE 754 standard is also known as a double-precision floating-point
number. It can represent a number as small as 4.9 x 10 -324 and as big as 1.7 x 10 308 (approx.) in magnitude. The range
includes only magnitude. It could be positive or negative. Here, 4.9 x 10 -324 is the smallest positive number greater than
zero that can be stored in a double variable.
 
Search WWH ::




Custom Search