Can anyone give a scenario of when to use String aaa = new String("abc") against String bbb="abc".
Printable View
Can anyone give a scenario of when to use String aaa = new String("abc") against String bbb="abc".
I have never seen someone use new String("abc"), that seems somewhat unnecessary.
Java API has provided this functionality. So there has to be a reason behind for it.
I presume you've already read the Javadocs? It is not usually needed. The example you show auto-creates a String with the characters "abc" to pass to the String constuctor. So, as the Javadocs say:
Sometimes the reason is for completness, sometimes it is an oversight.Quote:
Unless an explicit copy of original is needed, use of this constructor is unnecessary since Strings are immutable.
A portion of the API for this method:
One example where one might wish to copy: suppose you read a large File into a String. You then parse that String into smaller String's by calling substring, and explicitly keep references to these but not to the String of the full file. The String objects created from using substring still contain a reference to the original String they were parsed from (substring actually causes a new String to be created which references the original char array and the index values of the substring) - so although one might think the original String (actually its underlying char array) representing the full contents of the File is capable of being removed from memory, it is not. To avoid hanging onto these references, one can use the new String("") constructor to create copies of the substring, rather than referencing the original.Quote:
Unless an explicit copy of original is needed, use of this constructor is unnecessary since Strings are immutable.