What is difference between String str = "ABC"
and String str = new String("ABC")
?
Answer
In Java String
is a special object and allows you to create a new String
without necessarily doing new String("ABC")
. However String s = "ABC"
and String s = new String("ABC")
is not the same operation.
From the javadoc for new String(String original)
:
Initializes a newly created String object so that it represents the
same sequence of characters as the argument; [...]
Unless an explicit copy of original is needed, use of this constructor
is unnecessary since Strings are immutable.
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 String Constant Pool is where the collection of references to String
objects are placed.
String s = "prasad"
creates a new reference only if there isn't another one available. You can easily see that by using the ==
operator.
String s = "prasad";
String s2 = "prasad";
System.out.println(s == s2); // true
Image taken from thejavageek.com.
new String("prasad")
always create a new reference, in other words s
and s2
from the example below will have the same value but won't be the same object.
String s = "prasad";
String s2 = new String("prasad");
System.out.println(s == s2); // false
Image taken from thejavageek.com.
No comments:
Post a Comment