Java 实习生在Concat情况下的工作方式

Java 实习生在Concat情况下的工作方式,java,string,constants,pool,Java,String,Constants,Pool,为什么打印为假 根据我的理解,“xy”(即a+“y”)将被插入,当创建变量c时,编译器将检查字符串常量池中是否存在文字“xy”,如果存在,则它将为c分配相同的引用 注意:我不是在问equals()vs==运算符。分配给c的“xy”直接添加到字符串池(由intern使用)的原因是,该值在编译时已知 值a+“y”在编译时是未知的,但只有在运行时才知道。因为intern是一个昂贵的操作,除非开发人员显式地为其编码,否则通常不会执行该操作。如果字符串是由两个字符串文本串联而成的,那么它也将被intern

为什么打印为假

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

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

分配给
c
“xy”
直接添加到字符串池(由
intern
使用)的原因是,该值在编译时已知


a+“y”
在编译时是未知的,但只有在运行时才知道。因为
intern
是一个昂贵的操作,除非开发人员显式地为其编码,否则通常不会执行该操作。

如果字符串是由两个字符串文本串联而成的,那么它也将被intern

String a = "x";
String b = a + "y";
String c = "xy";
System.out.println(b==c);
下面是一个在Java中常见的字符串实习示例

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
然后是它的输出

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"; }

“xy”
是实习的,但是
a+“y”
的结果不是实习的,实习的
“xy”
也不是实习的结果,因为
a
不是最终的。除了其他答案之外,可能的重复:也要尝试,避免依赖它。如果代码被重用,这是很脆弱的。谢谢你的回复。好吧,那么变量b将出现在堆栈中,其中as c将引用字符串常量池?从技术上讲,
b
将引用堆中的字符串,但在其他方面是肯定的。
true
true
true
true
false
true