ZetCode

Java Float Class

Last modified: April 13, 2025

The java.lang.Float class wraps a value of primitive type float in an object. It provides methods for converting float values to strings and vice versa, as well as constants and methods useful when working with floats.

The Float class is part of Java's wrapper classes that allow primitive types to be used as objects. It's particularly useful when you need to store float values in collections or when you need to perform operations that require objects.

Float Class Methods

The Float class provides several methods for working with float values. These include methods for conversion, comparison, and checking special float values. The class also defines important constants like MAX_VALUE and MIN_VALUE.

public final class Float extends Number implements Comparable<Float> {
    public static final float MAX_VALUE = 3.4028235e+38f;
    public static final float MIN_VALUE = 1.4e-45f;
    public static final int SIZE = 32;
    
    public Float(float value) {...}
    public Float(String s) throws NumberFormatException {...}
    
    public static float parseFloat(String s) throws NumberFormatException {...}
    public static Float valueOf(float f) {...}
    public static Float valueOf(String s) throws NumberFormatException {...}
    
    public byte byteValue() {...}
    public short shortValue() {...}
    public int intValue() {...}
    public long longValue() {...}
    public float floatValue() {...}
    public double doubleValue() {...}
    
    public static boolean isNaN(float v) {...}
    public static boolean isInfinite(float v) {...}
    
    public boolean isNaN() {...}
    public boolean isInfinite() {...}
    
    public String toString() {...}
    public static String toString(float f) {...}
    public static int floatToIntBits(float value) {...}
    public static float intBitsToFloat(int bits) {...}
    
    public int compareTo(Float anotherFloat) {...}
    public boolean equals(Object obj) {...}
    public int hashCode() {...}
}

The code above shows the main methods and constants provided by the Float class. These methods allow for various operations on float values including parsing, conversion, and special value checking.

Creating Float Objects

Float objects can be created in several ways: using constructors, valueOf methods, or autoboxing. Each approach has its use cases and performance implications.

Main.java
package com.zetcode;

public class Main {

    public static void main(String[] args) {
        // Using constructor
        Float f1 = new Float(3.14f);
        Float f2 = new Float("3.14");
        
        // Using valueOf (recommended)
        Float f3 = Float.valueOf(3.14f);
        Float f4 = Float.valueOf("3.14");
        
        // Autoboxing
        Float f5 = 3.14f;
        
        System.out.println("f1: " + f1);
        System.out.println("f2: " + f2);
        System.out.println("f3: " + f3);
        System.out.println("f4: " + f4);
        System.out.println("f5: " + f5);
        
        // Getting primitive value
        float primitive = f1.floatValue();
        System.out.println("Primitive value: " + primitive);
    }
}

This example demonstrates different ways to create Float objects. The valueOf method is generally preferred over constructors as it may cache frequently requested values. Autoboxing automatically converts primitive float to Float.

Parsing and Converting Floats

The Float class provides methods to parse strings into float values and convert float values to strings. These operations are common when dealing with user input or displaying float values.

Main.java
package com.zetcode;

public class Main {

    public static void main(String[] args) {
        // String to float conversion
        String numStr = "123.456";
        float parsedFloat = Float.parseFloat(numStr);
        System.out.println("Parsed float: " + parsedFloat);
        
        // Float to String conversion
        Float f = 789.012f;
        String floatStr1 = f.toString();
        String floatStr2 = Float.toString(789.012f);
        
        System.out.println("toString(): " + floatStr1);
        System.out.println("Float.toString(): " + floatStr2);
        
        // Hexadecimal string representation
        String hexStr = Float.toHexString(123.456f);
        System.out.println("Hexadecimal: " + hexStr);
    }
}

This example shows how to convert between strings and float values. The parseFloat method converts strings to primitive float, while toString methods convert float values to strings. The toHexString method provides a hexadecimal representation.

Special Float Values

Float values can represent special cases like NaN (Not a Number) and infinity. The Float class provides methods to check for these special values and constants to represent them.

Main.java
package com.zetcode;

public class Main {

    public static void main(String[] args) {
        // Special float values
        float nan = Float.NaN;
        float posInf = Float.POSITIVE_INFINITY;
        float negInf = Float.NEGATIVE_INFINITY;
        
        System.out.println("NaN: " + nan);
        System.out.println("Positive Infinity: " + posInf);
        System.out.println("Negative Infinity: " + negInf);
        
        // Checking special values
        System.out.println("Is NaN? " + Float.isNaN(nan));
        System.out.println("Is Infinity? " + Float.isInfinite(posInf));
        
        // Operations with special values
        System.out.println("NaN == NaN? " + (nan == nan)); // false!
        System.out.println("Float.compare(nan, nan): " + 
                         Float.compare(nan, nan)); // 0
    }
}

This example demonstrates special float values and how to check for them. Note that NaN is not equal to itself according to == operator, but Float.compare handles this case correctly. Always use Float methods to check for special values.

Float Comparison

Comparing float values requires special care due to floating-point precision issues. The Float class provides methods for safe comparison and ordering of float values.

Main.java
package com.zetcode;

public class Main {

    public static void main(String[] args) {
        Float f1 = 1.0f / 3.0f;
        Float f2 = 0.33333334f; // Approximate 1/3
        
        // Direct comparison (not recommended)
        System.out.println("f1 == f2: " + (f1 == f2));
        
        // Using equals (considers precision)
        System.out.println("f1.equals(f2): " + f1.equals(f2));
        
        // Using compareTo
        System.out.println("f1.compareTo(f2): " + f1.compareTo(f2));
        
        // Comparing with epsilon (recommended for values)
        float epsilon = 0.000001f;
        boolean nearlyEqual = Math.abs(f1 - f2) < epsilon;
        System.out.println("Nearly equal: " + nearlyEqual);
    }
}

This example shows different ways to compare float values. Direct comparison with == is not recommended due to precision issues. The equals method checks exact equality, while compareTo provides ordering. For approximate equality, use an epsilon value.

Float Bit Manipulation

The Float class allows conversion between float values and their bit representation. This is useful for low-level operations or when precise control over the float representation is needed.

Main.java
package com.zetcode;

public class Main {

    public static void main(String[] args) {
        float value = -123.456f;
        
        // Convert float to bits
        int bits = Float.floatToIntBits(value);
        System.out.println("Float bits: " + Integer.toBinaryString(bits));
        
        // Convert bits back to float
        float reconstructed = Float.intBitsToFloat(bits);
        System.out.println("Reconstructed: " + reconstructed);
        
        // Special cases
        System.out.println("NaN bits: " + 
            Integer.toBinaryString(Float.floatToIntBits(Float.NaN)));
        System.out.println("Infinity bits: " + 
            Integer.toBinaryString(Float.floatToIntBits(Float.POSITIVE_INFINITY)));
    }
}

This example demonstrates how to convert between float values and their bit representations. The floatToIntBits method returns the 32-bit representation, while intBitsToFloat reconstructs the float value. This is useful for understanding float internals.

Float Constants

The Float class defines several useful constants that represent important float values. These constants are helpful when working with float ranges and limits.

Main.java
package com.zetcode;

public class Main {

    public static void main(String[] args) {
        System.out.println("Float size in bits: " + Float.SIZE);
        System.out.println("Maximum value: " + Float.MAX_VALUE);
        System.out.println("Minimum normal value: " + Float.MIN_NORMAL);
        System.out.println("Minimum positive value: " + Float.MIN_VALUE);
        System.out.println("Exponent bias: " + Float.MAX_EXPONENT);
        System.out.println("Minimum exponent: " + Float.MIN_EXPONENT);
        
        // Checking if a value is within float range
        double largeValue = 1e50;
        System.out.println(largeValue + " is finite float? " + 
            (largeValue <= Float.MAX_VALUE && largeValue >= -Float.MAX_VALUE));
    }
}

This example shows the important constants defined in the Float class. These constants represent the limits and characteristics of the float type. They're useful for range checking and understanding float capabilities.

Float vs Double

The Float class is similar to Double but works with 32-bit floating-point values instead of 64-bit. This example compares Float and Double in terms of precision and range.

Main.java
package com.zetcode;

public class Main {

    public static void main(String[] args) {
        // Precision comparison
        float floatPi = (float) Math.PI;
        double doublePi = Math.PI;
        
        System.out.println("Float PI: " + floatPi);
        System.out.println("Double PI: " + doublePi);
        System.out.println("Precision loss: " + (doublePi - floatPi));
        
        // Range comparison
        System.out.println("\nFloat range: " + Float.MIN_VALUE + " to " + Float.MAX_VALUE);
        System.out.println("Double range: " + Double.MIN_VALUE + " to " + Double.MAX_VALUE);
        
        // Memory usage
        System.out.println("\nFloat size: " + Float.SIZE + " bits");
        System.out.println("Double size: " + Double.SIZE + " bits");
    }
}

This example demonstrates the differences between Float and Double. Float has less precision (about 6-7 decimal digits) and smaller range than Double but uses half the memory. Choose Float when memory is critical and precision requirements are modest.

Source

Java Float Class Documentation

In this article, we've covered all major aspects of the Java Float class with practical examples. Understanding these methods is essential for proper handling of floating-point numbers in Java applications.

Author

My name is Jan Bodnar, and I am a dedicated programmer with many years of experience in the field. I began writing programming articles in 2007 and have since authored over 1,400 articles and eight e-books. With more than eight years of teaching experience, I am committed to sharing my knowledge and helping others master programming concepts.

List all Java tutorials.