There is almost no benefit to calling the String(String)
constructor with a literal string. There used to be a significant benefit to calling the String(String)
constructor with a different string expression.
The literal is already a String, and String objects are immutable. More generally, for any String expression passed to the String(String) constructor, the constructor is usually unnecessary, because the argument is already an immutable String.
From the String(String) constructor documentation:
public String(String original)
Initializes a newly created String object so that it represents the same sequence of characters as the argument; in other words, the newly created string is a copy of the argument string. Unless an explicit copy of original is needed, use of this constructor is unnecessary since Strings are immutable.
With older versions of Java (prior to 1.7.0_06), the String(String) constructor was more useful. A String created by String.substring()
could refer to the larger original String, and prevent it from being garbage collected. The String(String)
constructor cut the ties to the larger String.
You asked:
Q-1: ... The benefit of creating a duplicate object in heap?
Usually there is none. However, if you're using a String object in a context where object identity matters, you might want a different object. For example:
- You're using String objects as keys within a
IdentityHashMap
, and want only your own String objects to match.
- You want to synchronize on a string value provided by external code. You don't want any other code synchronizing on the same String object; it could lead to unexpected interference and deadlock. [This example provided by @biziclop in a comment below.]
Q-2: ... why does Java creates duplicate object in heap?
Because you explicitly asked it to with new String("my literal")
. If you use the new
operator, you get a new object.