【问题标题】:Why does ("str" + x == y) only compile for reference types?为什么 ("str" + x == y) 只编译引用类型?
【发布时间】:2014-08-12 07:48:16
【问题描述】:

为什么 == 运算符对引用的行为与对原始数据类型的行为不同?

String string1 = "myString";
String string2 = "myString";
int num1 = 10;
int num2 = 10;
System.out.println("Value is "+string1==string2);   //WORKS FINE 
System.out.println("Value is "+num1==num2);         //COMPILE TIME ERROR

我无法找出这背后的任何合乎逻辑的原因。

PS:打印语句中的括号是故意不使用的。
谢谢:)

【问题讨论】:

  • 如果您想到 == 运算符比较引用的值,这是有道理的。因此,在所有情况下,== 运算符都会比较其操作数的值。此外,您所拥有的是操作顺序问题,而不是 == 运算符的问题。

标签: java operator-keyword equality


【解决方案1】:

那是因为 operator precedence 你不能将字符串与 int 进行比较。

问题 1:

System.out.println("Value is "+num1==num2);  

+ 符号的优先级高于==,所以它会先执行+,然后再执行==

所以在+ 执行之后,这就是结果

 System.out.println("Value is 10"==num2);  //num1 is appended to the string

问题 2:

"Value is 10"==num2

这是编译错误的地方,字符串不能与int进行比较。

解决方案:

如果你想先比较 int 你需要把它包在括号内以避免编译时错误

System.out.println("Value is "+ (num1==num2)); 

【讨论】:

    【解决方案2】:

    这是operator precedence 的问题。您的第二个打印语句被解释为:

    System.out.println(("Value is "+num1)==num2);  // notice the parenthesis
    

    尝试将字符串与 int 进行比较,产生编译时错误。加括号解决问题:

    System.out.println("Value is " + (num1==num2));  // compiles
    

    Operators 中概述了 Java 运算符的优先级。

    现在,这个:

    // original:
    System.out.println("Value is "+string1==string2);
    
    // equivalent to:
    System.out.println(("Value is "+string1)==string2);
    

    之所以有效,是因为"Value is "+string1 本身就是一个字符串,因此将其与string2== 进行比较是有效的。

    【讨论】:

    • 嗨@arshajii。我通过尝试使用System.out.println("Value is "+string1==string1) 验证了这一点。我以前的知识说这会输出真,但它会打印出你的答案所解释的假。谢谢:)
    • @PiyushSaravagi 很高兴我能帮上忙。 :-)
    猜你喜欢
    • 1970-01-01
    • 2021-07-18
    • 1970-01-01
    • 2021-03-20
    • 2013-12-10
    • 1970-01-01
    • 1970-01-01
    • 2019-05-13
    • 2020-12-29
    相关资源
    最近更新 更多