-1

As per my knowledge, String s1 = new String("abc") create two object -

  1. One in heap
  2. Another in String Constant pool(SCP).

So,whenever we create String object using "new" keyword it will create a object in SCP.

Is it possible to have a String object present in heap but not in SCP?

  1. If No then What is the use of intern() method as it added the String object if it is not present in the SCP.
  2. If yes, could you please give an example.
Saheb
  • 49
  • 6

1 Answers1

-2

intern() method helps in comparing two String objects with == operator by looking into the pre-existing pool of string literals and it is faster than equals() method.

Though Java automatically interns all Strings by default, remember that we only need to intern strings when they are not constants, and we want to be able to quickly compare them to other interned strings. The intern() method should be used on strings constructed with new String() in order to compare them by == operator.

package test;

public class TestString {

public static void main(String[] args) {
    String s1 = "Test";
    String s2 = "Test";
    String s3 = new String("Test");
    final String s4 = s3.intern();
    System.out.println(s1 == s2);
    System.out.println(s2 == s3);
    System.out.println(s3 == s4);
    System.out.println(s1 == s3);
    System.out.println(s1 == s4);
    System.out.println(s1.equals(s2));
    System.out.println(s2.equals(s3));
    System.out.println(s3.equals(s4));
    System.out.println(s1.equals(s4));
    System.out.println(s1.equals(s3));
}

}

vivekdubey
  • 454
  • 2
  • 7