GeeCON Prague 2014*
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
Author

String assignment

shivam aggarwal
Greenhorn

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
Rancher

Joined: Mar 09, 2009
Posts: 600
Shivam:

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.

John.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39094
    
  23
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.
 
GeeCON Prague 2014
 
subject: String assignment