What's the difference between Float.POSITIVE_INFINITY and Float.MAX_VALUE?

No, they're not the same thing at all.

Float.MAX_VALUE is the largest finite value that can be represented in a float. You won't find any value greater than that, other than infinity. But you can perform all kinds of other operations on it.

Float.POSITIVE_INFINITY is, well, infinity. Most operations involving an infinity will end up with infinity (either positive or negative).

For example:

public class Test {
    public static void main(String[] args) {
        testOperations(Float.MAX_VALUE);
        testOperations(Float.POSITIVE_INFINITY);
    }

    public static void testOperations(float input) {
        System.out.println("input: " + input);
        System.out.println("input / 100: " + input / 100);
        System.out.println("input * 100: " + input * 100);
        System.out.println("-input: " + (-input));
        System.out.println();
    }
}

Output:

input: 3.4028235E38
input / 100: 3.4028236E36
input * 100: Infinity
-input: -3.4028235E38

input: Infinity
input / 100: Infinity
input * 100: Infinity
-input: -Infinity

To answer your specific question:

I came accross them looking for a value that would be greater than every other float or failing that all except the greatest. Does either meet that criteria?

Yes, Float.POSITIVE_INFINITY is, by its definition, the only Float that is greater than Float.MAX_VALUE. It is, however, something of a special case in terms of how it interacts with mathematical operations.

From the javadoc:

public static final float POSITIVE_INFINITY :

A constant holding the positive infinity of type float. It is equal to the value returned by Float.intBitsToFloat(0x7f800000).

public static final float MAX_VALUE :

A constant holding the largest positive finite value of type float, (2-2-23)·2127. It is equal to the hexadecimal floating-point literal 0x1.fffffeP+127f and also equal to Float.intBitsToFloat(0x7f7fffff).

So, as you can see, according to the very literal definition is that POSITIVE_INFINITY is greater than MAX_VALUE by one bit.

In terms of their utility, POSITIVE_INFINITY provides a value that you can use to recognize otherwise problematic mathematical expressions. The one used in the JDK source is 1.0f / 0.0f. The result of this expression is POSITIVE_INFINITY, indicating that you have exceeded the upper bound of reasonable mathematics, never to return. Given the two constants POSITIVE_INFINITY and NEGATIVE_INFINITY, you can check to see if a general expression has left the bounds of the useful Floats and whether it was the positive or negative door.

MAX_VALUE, on the other hand, represents the maximum value on which you can still apply normal mathematical operations. For example, MAX_VALUE - 1.0E32 is a (slightly) smaller number than MAX_VALUE. POSITIVE_INFINITY - 1.0E32, however, is still POSITIVE_INFINITY.

Tags:

Java