intern() behaving differently in Java 6 and Java 7

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

提交回复
热议问题