Reputation: 1944
Is using a String() constructor as against string literal beneficial in any scenario? Using string literals enable reuse of existing objects, so why do we need the public constructor? Is there any real world use? For eg., both the literals point to the same object.
String name1 = "name";//new String("name") creates a new object.
String name2 = "name";
Upvotes: 13
Views: 402
Reputation: 346260
One example where the constructor has a useful purpose: Strings created by String.substring()
share the underlying char[]
of the String
they're created by. So if you have a String
of length 10.000.000 (taking up 20MB of memory) and take its first 5 characters as substring then discard the original String
, that substring will still keep the 20MB object from being eligible for garbage collection. Using the String constructor on it will avoid that, as it makes a copy of only the part of the underlying char array that's actually used by the String
instance.
Of course, if you create and use a lot of substrings of the same String
, especially if they overlap, then you'd very much want them to share the underlying char[]
, and using the constructor would be counterproductive.
Upvotes: 18
Reputation: 8949
All good answers here, but I think it's worth pointing out that the Java treats literals quite different than Strings constructed the traditional way.
This is a good Q/A about it.
Upvotes: 0
Reputation: 15355
Since string is immutable, operations like substring keep the original string that might be long. Using the constructor to create new string from the substring will create a new string and will allow dropping the old string (to GC). This way might free up needed memory.
Example:
String longS = "very long";
String shortS = new String(longS.substring(4));
Upvotes: 3
Reputation: 36852
Because sometimes you might want to create a copy and not just have a new reference to the same string.
Upvotes: 0