How is creation of a String with new() different from a literal?
In this shot, we will discuss how the creation of a String using the new() method is different from that of a literal in Java.
The table and illustration below show the difference between String creation using the new() method and String creation using a String literal.
String creation using new() | String creation using String literal |
If we create a String using new(), then a new object is created in the heap memory even if that value is already present in the heap memory. | If we create a String using String literal and its value already exists in the string pool, then that String variable also points to that same value in the String pool without the creation of a new String with that value. |
It takes more time for the execution and thus has lower performance than using String literal. | It takes less time for the execution and thus has better performance than using new(). |
Example: String n1= new String(“Java”); String n2= new String(“Java”); String n3= new String(“Create”); | Example: String s1=”Java”; String s2=”Java”; String s3=”Create”; |
Code
The code below approaches this problem by creating String objects through both methods. We use the == operator for reference comparison and justify the difference between the objects.
class Main{public static void main(String[] args){String s1="Java";String s2="Java";String s3="Create";String n1= new String("Java");String n2= new String("Java");String n3= new String("Create");System.out.println(s1==s2);System.out.println(n1==n2);System.out.println(s3==n3);}}
Explanation
-
In line 1, we create a
Mainclass with amainfunction. -
In lines 5 to 7, we use
Stringliterals to initialize threeStringtype variables. -
In lines 9 to 11, we use
new()to initialize threeStringobjects. -
In line 13, we compare the references of
s1ands2, which point to the same objects, and therefore displaytrue. -
In line 14, we compare the references of
n1andn2, which do not point to the same objects, and therefore displayfalse. -
In line 15, we compare the references of
s3andn3, which do not point to the same objects, and displayfalse.