aspose file tools*
The moose likes Beginning Java and the fly likes When to use  new  for assigning value to a String variable Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "When to use  new  for assigning value to a String variable" Watch "When to use  new  for assigning value to a String variable" New topic
Author

When to use new for assigning value to a String variable

Vijay Tyagi
Ranch Hand

Joined: Feb 15, 2010
Posts: 52
String a="abcd";


String a=new String("abcd");

Are both of these statements correct ?
W. Joe Smith
Ranch Hand

Joined: Feb 10, 2009
Posts: 710
Yes, although I believe it is preferred to use String a="abdc"; over String a =new String("abcd");.


SCJA
When I die, I want people to look at me and say "Yeah, he might have been crazy, but that was one zarkin frood that knew where his towel was."
Siddhesh Deodhar
Ranch Hand

Joined: Mar 05, 2009
Posts: 118
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.


Good, Better, Best, Don't take rest until, Good becomes Better, and Better becomes Best.
Sidd : (SCJP 6 [90%] )
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39396
    
  28
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

Joined: Aug 16, 2005
Posts: 14269
    
  21

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.

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: When to use new for assigning value to a String variable