• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Jeanne Boyarsky
  • Ron McLeod
Sheriffs:
  • Paul Clapham
  • Liutauras Vilda
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
Bartenders:

String assignment

 
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
Rancher
Posts: 600
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Marshal
Posts: 80266
430
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
The harder you work, the luckier you get. This tiny ad brings luck - just not good luck or bad luck.
Smokeless wood heat with a rocket mass heater
https://woodheat.net
reply
    Bookmark Topic Watch Topic
  • New Topic