Java Tutorial Java Advanced Java References

Java float Keyword



The Java float keyword is a primitive data types. The float data type is a single-precision 32-bit IEEE 754 floating point. Its default value is 0.0f and default size is 32 bits (4 byte). The range of a float value is 1.40239846 x 10-45 to 3.40282347 x 1038.

Example: Create a float value

In the example below, variable x and y are created to store float values. Please note that, value with an "f" is used to represent the float value.

public class MyClass {
  public static void main(String[] args) {   
    //creating float values
    float x = 10.5f;
    float y = 10f;

    //printing variables
    System.out.println("x = " + x);
    System.out.println("y = " + y);    
  }
}

The output of the above code will be:

x = 10.5
y = 10.0

Example: Widening Casting (smaller to larger type)

A float value can be created by assigning a byte, a short, an int or a long data to a float variable. The compiler implicitly typecast these data types to float as shown in the output.

public class MyClass {
  public static void main(String[] args) {     
    byte num_byte = 10;

    //Widening Casting
    short num_short = num_byte;
    int num_int = num_short;
    long num_long = num_int;
    float num_float = num_long;

    //printing variables
    System.out.println("num_byte = " + num_byte); 
    System.out.println("num_short = " + num_short);
    System.out.println("num_int = " + num_int);
    System.out.println("num_long = " + num_long);
    System.out.println("num_float = " + num_float);  
  }
}

The output of the above code will be:

num_byte = 10
num_short = 10
num_int = 10
num_long = 10
num_float = 10.0

Example: Narrowing Casting (larger to smaller type)

For a larger data types like double, narrowing casting is required. The compiler explicitly typecast this data type to float as shown in the output.

public class MyClass {
  public static void main(String[] args) {   
    double num_double = 10.5d;

    //Narrowing Casting
    float num_float = (float) num_double;

    //printing variables
    System.out.println("num_double = " + num_double);
    System.out.println("num_float = " + num_float); 
  }
}

The output of the above code will be:

num_double = 10.5
num_float = 10.5

❮ Java Keywords