Difference between creating String using new operator and String literal

Number of View: 1629

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.

Stringnewoperatorpic

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

package javainterview;

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

}

Output :

false

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”.
Stringliterals

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

public class StringLiteralDemo {
public static void main(String[] args) {
String s1="Hello";
String s2="Hello";
System.out.println(s1==s2);
}

}

Output:

True

Related posts:

  1. String concatenation example using + operator
  2. core java interview questions and answers on Strings -part 50
  3. Difference between stack memory and heap memory in java

Leave a Reply

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

*

HTML tags are not allowed.