File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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
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: 46360
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
It's not a secret anymore!