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”; |
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);}}
In line 1, we create a Main
class with a main
function.
In lines 5 to 7, we use String
literals to initialize three String
type variables.
In lines 9 to 11, we use new()
to initialize three String
objects.
In line 13, we compare the references of s1
and s2
, which point to the same objects, and therefore display true
.
In line 14, we compare the references of n1
and n2
, which do not point to the same objects, and therefore display false
.
In line 15, we compare the references of s3
and n3
, which do not point to the same objects, and display false
.