Can anyone give a scenario of when to use String aaa = new String("abc") against String bbb="abc".
Welcome to the Java Programming Forums
The professional, friendly Java community. 21,500 members and growing!
The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.
>> REGISTER NOW TO START POSTING
Members have full access to the forums. Advertisements are removed for registered users.
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.Unless an explicit copy of original is needed, use of this constructor is unnecessary since Strings are immutable.
Need Java help? Check out the HotJoe Java Help forums!
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.Unless an explicit copy of original is needed, use of this constructor is unnecessary since Strings are immutable.
Last edited by copeg; July 2nd, 2012 at 10:01 AM. Reason: Clarification
tcstcs (July 3rd, 2012)