Difference between creating String using new operator and String literal

In How many ways we can create String objects or
What is difference between creating String objects using String s=”Hello”;

We can create String objects in the following two ways :

1)      By using String literals

2)      By creating String Object using new operator

Creating Strings by using new operator:

String s1=new String(”Hello”);

String s2=new String(”Hello”);

Though both s1 and s2 creates same sequence of characters “Hello” both creates two different objects when we create objects using new operator.


Example to demo both s1 and s2 pointing to different objects when objects created using new operator

[code lang=”java”]package javainterview;

public class StringNewDemo {
public static void main(String[] args) {
String s1=new String("Hello");
String s2=new String("Hello");


Output :


Creating Strings using String literals:

This is easiest way to create string.String literal is sequence of characters enclosed in double quotes.

String s1=”Hello”;

s1 is a String literal which refers to String object “Hello”.

Again if we define s2 as follows:

String s2=”Hello”;

S2 won’t create new Hello objects instead both s1 and s2 points to a common object “Hello”.

So when we create objects using string literals JVM creates Strings in special memory called String literal pool.

String literal pool is collection of string literals.To make java memory efficient string  literal pool was introduced.

So when an object is created using string literal first java compiler checks whether the same object exists in string literal pool,if object exists it won’t create new object.

If object is not found in pool,it creates a new object.

That is the reason in the above example both s1 and s2 points to common object “Hello”.

Example to demo both s1 and s2 points to same Object when “Hello” object is created using String literal

[code lang=”java”]public class StringLiteralDemo {
public static void main(String[] args) {
String s1="Hello";
String s2="Hello";




Leave a Reply

Your email address will not be published. Required fields are marked *