intern() behaving differently in Java 6 and Java 7

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

    FIRST CASE:

    In the first code snipped you are actually adding three Strings in the Pool of Strings. 1. s1 = "Good"
    2. s1 = "Goodmorning" (after concatenating) 3. s2 = "Goodmorining"

    While doing if(s1==s2), the objects are same but reference as different hence it is false.

    SECOND CASE:

    In this case you are using s1.intern(), which implies that if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.

    1. s1 = "Good"
    2. s1 = "Goodmorning" (after concatenating)
    3. For String s2="Goodmorning", new String is not added to the pool and you get reference of existing one for s2. Hence if(s1==s2) returns true.

提交回复
热议问题