Search code examples
javatype-promotion

Binary Numeric Promotion for Floats


In the JLS in 5.6.2. Binary Numeric Promotion:

When an operator applies binary numeric promotion to a pair of operands, each of which must denote a value that is convertible to a numeric type, the following rules apply, in order:

If any operand is of a reference type, it is subjected to unboxing conversion (§5.1.8).

Widening primitive conversion (§5.1.2) is applied to convert either or both operands as specified by the following rules:

If either operand is of type double, the other is converted to double.

Otherwise, if either operand is of type float, the other is converted to float.

Otherwise, if either operand is of type long, the other is converted to long.

Otherwise, both operands are converted to type int.

This confuses me because both http://www.mathcs.emory.edu/~cheung/Courses/170/Syllabus/04/mixed.html and https://alvinalexander.com/java/java-int-double-float-mixed-type-division-arithmetic-rules

state that

All floating point values (float and double) in an arithmetic operation (+, −, *, /) are converted to double type before the arithmetic operation in performed.

With my understanding, according to the JLS, adding 1 float and 1 integer would result in a float. However, according to the other sources, adding 1 float and 1 integer would result in a double?


Solution

  • When a source makes a claim contrary to the JLS, chances are good that it's wrong. In this case, the following demonstrates the behaviour that the JLS describes:

        Number n = 1 + 0.1f;
        System.out.println(n instanceof Float); // true
        System.out.println(n instanceof Double); // false