1

what is benefit of creating two object using new operator in string. Why two objects are created and what is their importance .

String s=new String("abc");

//creates two object 

//why 2 object creation is required.
3
  • 1
    There's very little benefit, and hardly ever required. Commented Apr 7, 2015 at 15:29
  • many tools will mark it as a minor bug and will suggest to use String s="abc" instead. P.S. why so sure it will create two objects? Commented Apr 7, 2015 at 17:50
  • @T.G: normally it should guarantee that if you use the constructor, a new object is created. string.valueOf may indeed use a "flyweight" pattern... Commented Apr 7, 2015 at 18:49

1 Answer 1

1

If you perform the following test:

String a = "foo";
String b = new String(a);
System.out.println(a == b);//returns false

So it means a and b are not the same object (this is probably mandatory because the new operator is used).

This can be useful if you would use the == to check if you are talking about the same string (thus not an equivalent string).

There is in this case however little use to do so, especially because String objects are immutable, as you can read in the manual:

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.

The only situation where it can be useful I think, if you would attach some kind of "message" aspect to the String, where a messageboard only accepts different object Strings. If you in that case want to insert the same message twice, you will need to make a copy of the String.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.