我是JAVA的新手,正在通过相等运算符。在尝试了几种操作数组合之后,我对Java中相等运算符(==)的兼容操作数的定义究竟是什么有些困惑。关于JAVA中的相等运算符(兼容操作数)的查询
int x = 23;
if (x == 23.3f) { // compiler accepts it. (may be because both are primitives)
int x = 23;
Double d = new Double(23.3);
if (x == d) { // compiler accepts it. (may be compatible pair of primitive and object reference)
int x = 23;
String s = "hello";
if (x == s) // compiler throws error - incompatible operands for == operator.
因此,它看起来对于我来说,对于相等运算符应该有一些兼容操作数的正式定义。请帮我澄清这个疑问。
字符串有'.equals'方法。并在你的最后一个'如果'它显然,他们是不兼容的,因为你是比较一个对象(字符串)与原始类型(int,long,double ...) – 2014-09-03 08:30:44
我明白.equals在那里,但我的查询是专门针对==的。如果你看到我的第二个例子,我将Object与Object(Double。)进行比较,然后编译器接受它。 – pankaj 2014-09-03 08:39:00