When should we use intern method of String on String literals

后端 未结 14 793
生来不讨喜
生来不讨喜 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:46

    By using heap object reference if we want to get corresponding string constant pool object reference, then we should go for intern()

    String s1 = new String("Rakesh");
    String s2 = s1.intern();
    String s3 = "Rakesh";
    
    System.out.println(s1 == s2); // false
    System.out.println(s2 == s3); // true
    

    Pictorial View

    Step 1: Object with data 'Rakesh' get created in heap and string constant pool. Also s1 is always pointing to heap object.

    Step 2: By using heap object reference s1, we are trying to get corresponding string constant pool object referenc s2, using intern()

    Step 3: Intentionally creating a object with data 'Rakesh' in string constant pool, referenced by name s3

    As "==" operator meant for reference comparison.

    Getting false for s1==s2

    Getting true for s2==s3

    Hope this help!!

提交回复
热议问题