intern() behaving differently in Java 6 and Java 7

后端 未结 9 1042
梦谈多话
梦谈多话 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:13

    The result code dependents runtime:

    class Test {
         public static void main(String... args) {
            String s1 = "Good";
            s1 = s1 + "morning";
            System.out.println(s1 == s1.intern()); // Prints true for jdk7, false - for jdk6.
        }
    }
    

    If you write like this:

    class Test {
         public static void main(String... args) {
            String s = "GoodMorning";
            String s1 = "Good";
            s1 = s1 + "morning";
            System.out.println(s1 == s1.intern()); // Prints false for both jdk7 and jdk6.
        }
    }
    

    the reason is ' ldc #N ' (Load string from constant pool) and String.intern() both will use StringTable in hotspot JVM. For detail I wrote a pool english article: http://aprilsoft.cn/blog/post/307.html

    0 讨论(0)
  • 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?

    0 讨论(0)
  • 2020-11-29 22:18

    You need to use s1.equals(s2). Using == with String objects compares the object references themselves.

    Edit: When I run your second code snippet, I do not get "both are equal" printed out.

    Edit2: Clarified that references are compared when you use '=='.

    0 讨论(0)
提交回复
热议问题