Java float keyword
The Java float keyword is a primitive data type. It is a single-precision 32-bit IEEE 754 floating point. It is used to declare the variables and methods. It represents the fractional numbers.
Points to remember
- The float covers a range from 1.40129846432481707e-45 to 3.40282346638528860e+38 (positive or negative).
- Its default value is 0.0f.
- Its default size is 4 byte.
- It can be used to save memory in large arrays of floating point numbers.
- It is not a good approach to use float for precise values, such as currency.
Examples of Java float keyword
Example 1
Let’s see a simple example to display float type variable.
Output:
num1: 5.5 num2: 5.0
Example 2
In this example, we provide integer value to float variable. Here, compiler implicitly typecast integer to float and display the corresponding value in fractional form.
Output:
num1: 5.0 num2: 10.0
Example 3
In this example, we provide bigger decimal value.
Output:
num1: 5.812167E8 num2: 7.8368497
Example 4
In this example, we provide float value to the decimal variable.
Output:
Exception in thread "main" java.lang.Error: Unresolved compilation problem: Type mismatch: cannot convert from double to float
Example 5
In this example, we provide the end range of decimal value.
Output:
num1: 1.4E-45 num2: 3.4028235E38
Example 6
In this example, we provide the value in scientific notation
Output:
num1: 1873.2 num2: 1873.2
Example 7
In this example, we create a method returning float value.
Output:
62.5