-2

这就是我所说的:

package finalExample;

public class FinalExample {

public static void main(String args[]) {

    final String str1 = "str";
    final String str2 = "ing";

    String str11 = "str";
    String str22 = "ing";

    System.out.println("Using equals() for non final :" + str11.equals(str22));
    System.out.println("Using == for non final :" + (str11==str22));
    System.out.println("MAGIC Using == for non final :" + str11==str22);

    System.out.println("Using equals() for final :" + str1.equals(str2));
    System.out.println("Using == for final :" + (str1==str2));
    System.out.println("MAGIC Using == for final :" + str1==str2);
}

}

输出是:

Using equals() for non final :false
Using == for non final :false
false
Using equals() for final :false
Using == for final :false
false

两个 MAGIC 语句都不会打印。为什么会这样?

4

3 回答 3

11

运算符的+绑定优先级高于==运算符,因此您的表达式为:

"MAGIC Using == for final :" + str1==str2
("MAGIC Using == for final :" + str1)==str2
(a new String object created for the comparison can't)==str2
false
于 2013-10-17T06:25:09.953 回答
3

你正在评估

"MAGIC Using == for non final :" + str11

这是一个字符串,然后与 str2 进行比较

于 2013-10-17T06:25:25.337 回答
2

我认为它确实打印了。结果是假的;所以它打印“假”你可以认为它: res = "MAGIC Using == for final :" + str1 ; println(res == str2) 所以它打印错误。

于 2013-10-17T06:29:40.557 回答