When should we use intern method of String on String literals

后端 未结 14 963
生来不讨喜
生来不讨喜 2020-11-22 08:11

According to String#intern(), intern method is supposed to return the String from the String pool if the String is found in String pool, otherwise a new string

14条回答
  •  独厮守ぢ
    2020-11-22 08:28

    Java automatically interns String literals. This means that in many cases, the == operator appears to work for Strings in the same way that it does for ints or other primitive values.

    Since interning is automatic for String literals, the intern() method is to be used on Strings constructed with new String()

    Using your example:

    String s1 = "Rakesh";
    String s2 = "Rakesh";
    String s3 = "Rakesh".intern();
    String s4 = new String("Rakesh");
    String s5 = new String("Rakesh").intern();
    
    if ( s1 == s2 ){
        System.out.println("s1 and s2 are same");  // 1.
    }
    
    if ( s1 == s3 ){
        System.out.println("s1 and s3 are same" );  // 2.
    }
    
    if ( s1 == s4 ){
        System.out.println("s1 and s4 are same" );  // 3.
    }
    
    if ( s1 == s5 ){
        System.out.println("s1 and s5 are same" );  // 4.
    }
    

    will return:

    s1 and s2 are same
    s1 and s3 are same
    s1 and s5 are same
    

    In all the cases besides of s4 variable, a value for which was explicitly created using new operator and where intern method was not used on it's result, it is a single immutable instance that's being returned JVM's string constant pool.

    Refer to JavaTechniques "String Equality and Interning" for more information.

提交回复
热议问题