了解 Java 中的运算符 ==

Understanding operator == in Java

JLS 8, chapt 15.21 指定了两个名为 floating point equality testinteger equality test 的概念,如下所示:

If the promoted type of the operands is int or long, then an integer equality test is performed.

If the promoted type is float or double, then a floating-point equality test is performed.

浮点数定义如下:

Floating-point equality testing is performed in accordance with the rules of the IEEE 754 standard:

因此,我们可以参考 IEEE 754 来描述浮点相等性的行为。但是 ints 呢? JLS 在哪里指定它如何执行整数相等性测试?

由于 int and all other integral types are signed two's complement 在 Java 中,您不必担心有两种不同的方式来表示 0。

由于您正在寻找参考,the JLS §4.2. 提供了一个:

If an integer operator other than a shift operator has at least one operand of type long, then the operation is carried out using 64-bit precision, and the result of the numerical operator is of type long. If the other operand is not long, it is first widened (§5.1.5) to type long by numeric promotion (§5.6).

Otherwise, the operation is carried out using 32-bit precision, and the result of the numerical operator is of type int. If either operand is not an int, it is first widened to type int by numeric promotion.