Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

String assignment

 
shivam aggarwal
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 600
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 49733
69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic