Consider the following snippet:
int i = 99999999;
byte b = 99;
short s = 9999;
Integer ii = Integer.valueOf(9); // should be within cache
I will first explain precisely when == is a reference equality, and precisely when it's a numerical equality. The conditions for reference equality is simpler, so it will be explained first.
If the operands of an equality operator are both of either reference type or the null type, then the operation is object equality.
This explains the following:
System.out.println(new Integer(0) == new Integer(0)); // "false"
Both operands are Integer, which are reference types, and that's why the == is reference equality comparison, and two new objects will never be == to each other, so that's why it prints false.
For == to be numerical equality, at least one of the operand must be a numeric type; this is specified as follows:
If the operands of an equality operator are both of numeric type, or one is of numeric type and the other is convertible to numeric type, binary numeric promotion is performed on the operands. If the promoted type of the operands is
intorlong, then an integer equality test is performed; if the promoted type isfloat ordouble`, then a floating-point equality test is performed.Note that binary numeric promotion performs value set conversion and unboxing conversion.
Thus, consider the following:
System.out.println(new Integer(0) == 0); // "true"
This prints true, because:
int typeint== is a numerical equality operation== and != are reference types, it will always be a reference equality operation