• 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

When to use new for assigning value to a String variable

 
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
String a="abcd";


String a=new String("abcd");

Are both of these statements correct ?
 
Ranch Hand
Posts: 710
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Yes, although I believe it is preferred to use String a="abdc"; over String a =new String("abcd");.
 
Ranch Hand
Posts: 118
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
String a="abcd";

- One object is created in string pool i.e. "abcd".

String b=new String("abcd");

- 2 objects are created. One object is created in string pool i.e. "abcd".. second in non-pool memory.


In this case a==b will return false. First approach is mostly used.
 
Marshal
Posts: 79239
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Have a look at the String constructors. Also try searching, because this subject or similar comes up about every other week, but "new String" will give you hundreds of irrelevant results, I am afraid.
 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Vijay Tyagi wrote:String a="abcd";

String a=new String("abcd");

Are both of these statements correct ?


Both are correct (in the sense that you don't get a compiler or run-time error) but you should never need to use the second one. The second statement is less efficient (it always creates a new String object and copies the content of the String object that you pass in) and the code is also unnecessarily longer. Note that String objects in Java are immutable, so you do not need to make defensive copies of String objects.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic