Reputation: 50
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.
Upvotes: 1
Views: 126
Reputation: 476544
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
.
Upvotes: 1