Difference between creating string with and without new operator?

Q2. Is there any difference between creating string with and without new operator?

 String s1 = "abc";
           String s2 = new String("abc");
           String s3 = "abc";
           String s4 = new String("abc");
           String s5 = new String("abc").intern();

When String is created without new operator, it will be created in string pool.

When String is created using new operator, it will force JVM to create new string in heap (not in string pool).

Let’s discuss step-by-step what will happen when below 5 statements will be executed >

        String s1 = "abc";

  1. String s1 = "abc";

No string with “abc” is there in pool, so JVM will create string in string pool and s1 will be a reference variable which will refer to it.

  1. String s2 = new String("abc");

string is created using new operator, it will force JVM to create new string in heap (not in string pool).

  1. String s3 = "abc";

string with “abc” is there in pool, so s3 will be a reference variable which will refer to “abc” in string pool.

  1. String s4 = new String("abc");

string is created using new operator, it will force JVM to create new string in heap (not in string pool).

  1. String s5 = new String("abc").intern();

string is created using new operator but intern method has been invoked on it, so s5 will be a reference variable which will refer to “abc” in string pool.

How intern method works in java ?

  • with intern method when you are creating a string it will create a new string in string pool and check wether the same string is present in pool or not if it is present it will point to the same other wise new object will be created