String a = "x";
String b = a + "y";
String c = "xy";
System.out.println(b==c);


为什么打印错误?

根据我的理解,“ xy”(即a +“ y”)将被插入,并且在创建变量c时,编译器将检查字符串常量池中是否存在文字“ xy”(如果存在),则它将为c分配相同的引用。

注意:我不是在问equals()vs ==运算符。

最佳答案

如果一个字符串是由两个字符串文字串联而成的,则它也会被插入。

String a = "x";
String b = a + "y"; // a is not a string literal, so no interning
------------------------------------------------------------------------------------------
String b = "x" + "y"; // on the other hand, "x" is a string literal
String c = "xy";

System.out.println( b == c ); // true


这是在Java中进行字符串实习的常见示例

class Test {
    public static void main(String[] args) {
        String hello = "Hello", lo = "lo";

        System.out.print((hello == "Hello") + " ");
        System.out.print((Other.hello == hello) + " ");
        System.out.print((other.Other.hello == hello) + " ");
        System.out.print((hello == ("Hel"+"lo")) + " ");
        System.out.print((hello == ("Hel"+lo)) + " ");
        System.out.println(hello == ("Hel"+lo).intern());
    }
}

class Other { static String hello = "Hello"; }


跟着它的输出

true
true
true
true
false
true

08-04 17:39