| 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: 117
|
|
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: 32675
|
|
|
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
Bartender
Joined: Aug 16, 2005
Posts: 12921
|
|
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 7 API documentation
Scala Notes - My blog about Scala
|
 |
 |
|
|
subject: When to use new for assigning value to a String variable
|
|
|