File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

When to use new for assigning value to a String variable

 
Vijay Tyagi
Ranch Hand
Posts: 52
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
String a="abcd";


String a=new String("abcd");

Are both of these statements correct ?
 
W. Joe Smith
Ranch Hand
Posts: 710
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, although I believe it is preferred to use String a="abdc"; over String a =new String("abcd");.
 
Siddhesh Deodhar
Ranch Hand
Posts: 118
  • 0
  • Mark post as helpful
  • send pies
  • 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.
 
Campbell Ritchie
Sheriff
Pie
Posts: 47293
52
  • 0
  • Mark post as helpful
  • send pies
  • 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.
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Pie
Posts: 15150
31
Android IntelliJ IDE Java Scala Spring
  • 0
  • Mark post as helpful
  • send pies
  • 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.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic