How comparison Object and primitive, with operator == works in Java? [duplicate]

早过忘川 提交于 2019-11-29 15:34:38

As ever, the Java Language Specification is the appropriate resource to consult

From JLS 15.21.1 ("Numerical Equality Operators == and !="):

If the operands of an equality operator are both of numeric type, or one is of numeric type and the other is convertible (§5.1.8) to numeric type, binary numeric promotion is performed on the operands (§5.6.2).

Note that binary numeric promotion performs value set conversion (§5.1.13) and may perform unboxing conversion (§5.1.8).

Then from 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).
  • [...]

So the Long is unboxed to a long. Your code is equivalent to:

Long objectLong = 555l;
long primitiveLong = 555l;

// This unboxing is compiler-generated due to numeric promotion
long tmpLong = objectLong.longValue();

System.out.println(tmpLong == primitiveLong); 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!