编程语言
首页 > 编程语言> > java-什么时候可以使用“ ==”运算符?

java-什么时候可以使用“ ==”运算符?

作者:互联网

我从jls找到了报价:

The equality operators may be used to compare two operands that are
convertible (§5.1.8) to numeric type, or two operands of type boolean
or Boolean, or two operands that are each of either reference type or
the null type
. All other cases result in a compile-time error.

但是这段代码

   String str= "";
   Number num = 1;
   System.out.println(str == num);

每个操作数都是参考!

说这是不兼容的类型.

jls在哪里说这些类型应该兼容?

解决方法:

section 15.21.3(参考相等运算符==和!=)中:

It is a compile-time error if it is impossible to convert the type of either operand to the type of the other by a casting conversion (§5.5). The run-time values of the two operands would necessarily be unequal.

标签:jls,java,reference,equality
来源: https://codeday.me/bug/20191010/1885818.html