Possible Duplicate:
What is the purpose of the expression “new String(…)” in Java?
I know that String s = new String("Hello World") should be avoided as it will create extra space for “Hello World” which is unnecessary in most cases.
Related question explaining why String s = new String("Hello World")should be avoided is here:
What is the difference between "text" and new String("text")?
But when do we need to use String s = new String("Hello World"), instead of String s = "Hello World"? This is a interview question I experienced.
If String s = new String("Hello World")should be avoided in most cases, why Java still allows that?
1) String s = “text”;
This syntax will allocate memory for “text” in heap. and each time when you will assign this “text” to other variable it will return the same memory reference to each time.
for Exp –
will print – Yes
but
String s = new String(“text”);
Always create a new location in memory and returns a new reference each time.
for Exp –
will print – No