我什么时候可以使用“==”运营商? [英] When can I use "==" operator?

查看:99
本文介绍了我什么时候可以使用“==”运营商?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从jls找到了引用:

I have found quote from jls:


相等运算符可用于比较
convertible的两个操作数( §5.1.8)数字类型,或boolean
或Boolean类型的两个操作数,或两个操作数,每个操作数都是引用类型或
null类型
。所有其他情况都会导致编译时错误。

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);

每个操作数都是引用!

表示这是不兼容的类型。

said that it is incompatible types.

在jls中哪些地方说这些类型应该兼容?

Where did in jls say that these types should be compatible ?

推荐答案

第15.21节中。 3 (参考等式运算符==和!=):

In section 15.21.3 (Reference Equality Operators == and !=):


如果无法进行编译时错误通过强制转换将第一个操作数的类型转换为另一个操作数的类型(第5.5节)。两个操作数的运行时值必然不相等。

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.

这篇关于我什么时候可以使用“==”运营商?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆