Forums Register Login

When to use new for assigning value to a String variable

+Pie Number of slices to send: Send
String a="abcd";


String a=new String("abcd");

Are both of these statements correct ?
+Pie Number of slices to send: Send
Yes, although I believe it is preferred to use String a="abdc"; over String a =new String("abcd");.
+Pie Number of slices to send: Send
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.
+Pie Number of slices to send: Send
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.
+Pie Number of slices to send: Send
 

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.
Good heavens! What have you done! Here, try to fix it with this tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 1017 times.
Similar Threads
accessing lost string objects in the "string pool"
String
String question
stringBuffer VS string
difference between String a ="abcd" and String b= new String ("abcd")
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 29, 2024 00:27:58.