Java - Data Types float type

What is float type?

Java float data type uses 32 bits to store a floating-point number in the IEEE 754 standard format.

float type value range is from 1.4 x 10^-45 to 3.4 x 10^38.

A floating-point number represented in 32 bits according to IEEE 754 standard is also known as a single-precision floating-point number.

float type literal

real numbers ending with f or F are Java float literals.

A float literal can be expressed in the following two formats:

  • Decimal number format
  • Scientific notation

float Decimal number format

Examples of float literals in decimal number format are as follows:

  
f1 = 1F; 
f2 = 1.F; 
f3 = 1.0F; 
f4 = 1.51F; 
f5 = 0.0F; 
f6 = 1.78f; 

Demo

public class Main {
  public static void main(String[] args) {
    float f1 = 1F; 
    float f2 = 1.F; 
    float f3 = 1.0F; 
    float f4 = 1.51F; 
    float f5 = 0.0F; 
    float f6 = 1.78f; 
    System.out.println(f1);//from  w w w  .  j  a va2s. co m
    System.out.println(f2);
    System.out.println(f3);
    System.out.println(f4);
    System.out.println(f5);
    System.out.println(f6);

  }
}

Result

float Scientific notation

3.25 is written using exponential forms such as 32.5 x 10^-1 or 0.325 x 10^1.

In scientific notation, the number 32.5 x 10^-1 is written as 32.5E-1.

As float literal, it can be written as 32.5E-1F or 32.5E-1f.

All of the following float literals denote the same real number 32.5:

  
3.25F 
32.5E-1F 
0.325E+1F 
0.325E1F 
0.0325E2F 
0.0325e2F 
3.25E0F 

Demo

public class Main {
  public static void main(String[] args) {
    float f1 = 3.25F;
    float f2 = 32.5E-1F; 
    float f3 = 0.325E+1F ; 
    float f4 = 0.325E1F; 
    float f5 = 0.0325E2F; 
    float f6 = 0.0325e2F; 
    float f7 = 3.25E0F;

    System.out.println(f1);// w w  w.  ja va  2s.co m
    System.out.println(f2);
    System.out.println(f3);
    System.out.println(f4);
    System.out.println(f5);
    System.out.println(f6);
    System.out.println(f7);
  }
}

Result

Out of range value

Cannot assign a float literal to a float variable greater than the maximum value of float(3.4E38F approx)

// A compile-time error. 
float fTooBig = 3.5E38F; 

Cannot assign a float literal to a float variable less than the minimum value (greater than zero) of float 1.4E-45F

// A compile-time error. 
float fTooSmall = 1.4E-46F; 

Exercise