What is the difference between the following two initializations in Java?
String a = new String();
String b = new String("");
When we create a String object using the new() operator, it always creates a new object in heap memory. On the other hand, if we create an object using String literal syntax e.g. “Baeldung”, it may return an existing object from the String pool, if it already exists.
By new keyword : Java String is created by using a keyword “new”. For example: String s=new String(“Welcome”); It creates two objects (in String pool and in heap) and one reference variable where the variable 's' will refer to the object in the heap.
In other words doing String s = new String("ABC") creates a new instance of String , while String s = "ABC" reuse, if available, an instance of the String Constant Pool.
The statement String s = “hello” is initialized to s and creates a single interned object. While String s = new String(“hello”); creates two string objects, one – interned object, two – object on the heap.
Well, they are almost the same.
public static void main(String[] args) { String s1 = new String(); String s2 = new String(""); System.out.println(s1.equals(s2)); // returns true. }
Minor differences (rather insignificant) :
new String();
takes less time to execute than new String("");
because the copy constructor does a lot of stuff.
new String("")
adds the empty String (""
) to the String constants pool if it is not already present.
Other than this, there are no other differences
Note : The use of new String("abc")
is almost always bad because you will be creating 2 Strings one on String constants pool and another on heap with the same value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With