intern() behaving differently in Java 6 and Java 7

后端 未结 9 1068
梦谈多话
梦谈多话 2020-11-29 21:36
class Test {
    public static void main(String...args) {
        String s1 = \"Good\";
        s1 = s1 + \"morning\";
        System.out.println(s1.intern());
              


        
9条回答
  •  无人及你
    2020-11-29 22:17

    In jdk6: String s1="Good"; creates a String object "Good" in constant pool.

    s1=s1+"morning"; creates another String object "morning" in constant pool but this time actually JVM do: s1=new StringBuffer().append(s1).append("morning").toString();.

    Now as the new operator creates an object in heap therefore the reference in s1 is of heap not constant pool and the String s2="Goodmorning"; creates a String object "Goodmorning" in constant pool whose reference is stored in s2.

    Therefore, if(s1==s2) condition is false.

    But what happens in jdk7?

提交回复
热议问题