This week's giveaway is in the Spring forum.
We're giving away four copies of REST with Spring (video course) and have Eugen Paraschiv on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes String assignment Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "String assignment" Watch "String assignment" New topic

String assignment

shivam aggarwal

Joined: Oct 15, 2009
Posts: 8
what is the diff. between statements

String s="abc";
String s=new String("abc");

and in what cond. is each of these used?
John de Michele

Joined: Mar 09, 2009
Posts: 600

It depends. If, for example, you already had an earlier call like this:

then, your first instance would refer to the same String object in the String pool as r does. Otherwise, it would create a new String in the String pool. Your second instance creates a new String with the value "abc" regardless of whether a String with that value already exists, and should be avoided.

Campbell Ritchie

Joined: Oct 13, 2005
Posts: 45277
Not quite. The first statement creates one String, which is created at class loading time. That is the "abc" on the right. Then it applies the name "s" to it. You have one String. This is independent of whether there is a String "r" or not. If you had another reference as John de Michele showed, you would still have one String, but now with two names, "s" and "r".

The second, as John de Michele has told you, creates two objects, "abc" and s which is identical, but a second object. Remember that "abc" is still available for use anywhere else. The second style is, as you have been told, usually best avoided.
I agree. Here's the link:
subject: String assignment
jQuery in Action, 3rd edition