• 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

using string

 
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi all,

Can anybody please clarify me .

Are there any particular rules about using
String s =new String("S") and String s="S". when to use what?

Thank you
 
Ranch Hand
Posts: 99
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Always better to use
String s = "S";//Line 1 rather than
String s = new String("S"); //Line 2

Reason :

Line 2 will always create a new String object containing a value "S", while Line 1 wont create a String object of "S", if a String object with value "S" is already in the pool.
 
Ranch Hand
Posts: 86
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
String s1="abc"; this statement will create a String object into heap & store a reference of this object into StringPool.
so,
Whenever you write ,
String s2="abc"; this statement will not create any object again & it will simply refer the String object that has a reference in StringPool having the same content.

Now, When you write,
String s3=new String("abc"); now you are telling the compiler to implicitly create a String Object.

If you want s3 to refer the first object s1, you have to use s3.intern();


So, For performance point of view its better to create String Object using String literal.

 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic