float

About

  • Definition: The float data type is a primitive data type in Java used to represent a 32-bit single-precision floating-point number. It is mainly used for saving memory in large arrays of floating-point numbers where precision is not a critical concern.

  • Size: Occupies 4 bytes (32 bits) in memory.

  • Value Range: Approximately 1.4E-45 to 3.4E+38 for positive values (from -3.4E+38 to 3.4E+38 for negative and positive values combined), with about 6-7 decimal digits of precision.

  • Default Value: The default value of float is 0.0f.

  • Wrapper Class: The wrapper class for float is Float, located in java.lang.

Characteristics of float

  1. Floating-Point Representation: float is used to represent numbers that require fractional values but where memory efficiency is a concern.

  2. Memory Usage: It consumes 4 bytes (32 bits) of memory, which is smaller than double, which uses 8 bytes (64 bits).

  3. Precision: float has a precision of about 6-7 decimal places, which is less than double, which can represent up to 15 decimal places. It is suitable when precise accuracy is not crucial.

  4. Scientific Notation: float values can be represented in scientific notation, such as 3.14e2, which represents 314.0.

  5. IEEE 754 Standard: float in Java follows the IEEE 754 standard for floating-point arithmetic. It includes special values like NaN(Not-a-Number), Infinity, and -Infinity.

  6. Promotion in Expressions: If a float is mixed with a double, the float is promoted to a double in arithmetic expressions, as doublehas a larger range and higher precision.

  7. Performance Considerations: float is generally faster and uses less memory compared to double, but its lower precision may result in rounding errors in calculations.

  8. Avoiding Precision Loss: For calculations requiring higher precision, double is often preferred over float. But for memory-constrained applications (e.g., graphics, scientific calculations), float is useful.

  9. Memory Usage: A float occupies 4 bytes (32 bits). This is smaller compared to double's 8 bytes, making float more memory-efficient.

Operations with float

Arithmetic and Logical Operations

Operation

Example

Description

Arithmetic Operations

float sum = a + b;

Addition, subtraction, multiplication, division.

Comparison Operations

a == b, a > b, etc.

Compares two float values.

Bitwise Operations

Not supported directly on float

float does not support bitwise operators like &, `

Conversion Methods

Conversion

Method

Example

float to String

String.valueOf(float)

String.valueOf(12.34f)"12.34"

String to float

Float.parseFloat(String)

Float.parseFloat("12.34")12.34f

float to double

Implicit conversion

double result = 12.34f;

double to float

Explicit cast (float)

(float) 12.3412.34f

Wrapper Class Example (Float)

Method

Description

Float.valueOf(float f)

Returns a Float object for the given float value.

Float.parseFloat(String s)

Parses the string argument as a float.

Float.toString(float f)

Converts float to its String representation.

Float.isNaN(float f)

Checks if the float value is NaN.

Float.isInfinite(float f)

Checks if the float value is positive or negative infinity.

Common Mistakes

  1. Loss of Precision: Since float has only about 6-7 decimal digits of precision, rounding errors can occur in calculations that require higher precision. For example:

    float num1 = 0.1f;
    float num2 = 0.2f;
    System.out.println(num1 + num2); // Output might not be exactly 0.3
  2. Mixing with double: float values are automatically promoted to double in expressions that involve both float and double. This could result in unnecessary memory usage or unexpected results if not carefully managed.

  3. Comparison with NaN: NaN (Not a Number) is not equal to any number, including itself. So, comparing NaN to any value directly may not behave as expected:

    float nanValue = Float.NaN;
    System.out.println(nanValue == nanValue); // Output: false

Examples

Basic Example

public class FloatExample {
    public static void main(String[] args) {
        float num1 = 10.5f;
        float num2 = 20.25f;

        // Arithmetic operations
        float sum = num1 + num2; 
        System.out.println("Sum: " + sum); // Sum: 30.75

        // Comparing values
        System.out.println("Is num1 greater than num2? " + (num1 > num2)); // Is num1 greater than num2? false

        // Casting
        int smallerValue = (int) num1; // Cast float to int
        System.out.println("Casted Value: " + smallerValue); // Casted Value: 10
    }
}

Using float in Arrays

public class FloatArrayExample {
    public static void main(String[] args) {
        float[] floatArray = {10.5f, 20.25f, 30.75f};

        for (float value : floatArray) {
            System.out.println(value); // 10.5, 20.25, 30.75
        }
    }
}

Converting float to String

public class FloatConversion {
    public static void main(String[] args) {
        float num = 12.34f;
        String str = Float.toString(num); 
        System.out.println("Float as String: " + str); // Float as String: 12.34
    }
}

Using float in Streams

import java.util.stream.FloatStream;

public class FloatStreamExample {
    public static void main(String[] args) {
        float[] values = {1.2f, 3.4f, 5.6f, 7.8f};

        float average = FloatStream.of(values)
                                   .average()
                                   .orElse(0.0f);

        System.out.println("Average: " + average); // Average: 4.5
    }
}

Wrapper Class Example

public class FloatWrapperExample {
    public static void main(String[] args) {
        String strValue = "12.34";
        float parsedValue = Float.parseFloat(strValue); 
        System.out.println("Parsed Value: " + parsedValue); // Parsed Value: 12.34

        float minValue = Float.MIN_VALUE; 
        float maxValue = Float.MAX_VALUE; 
        System.out.println("Min Value: " + minValue); // Min Value: 1.4E-45
        System.out.println("Max Value: " + maxValue); // Max Value: 3.4028235E38
    }
}

Last updated

Was this helpful?