When should you use String s = new String ("Hello World")?

Possible duplicate:
What is the purpose of the expression "new String (...)" in Java?

I know what to avoid String s = new String("Hello World"), as it will create additional space for "Hello World", which in most cases is not necessary.

A related question explaining why to avoid String s = new String("Hello World"):

What is the difference between "text" and the new String ("text")?

But when do we need to use String s = new String("Hello World")instead String s = "Hello World"? This is a question of an interview that I experienced.

If in most cases you should avoid String s = new String("Hello World"), why does Java still allow this?

+5
source share
1 answer

1) String s = "text"; This syntax will allocate memory for the "text" on the heap. and each time you assign this “text” to another variable, it will return the same memory reference every time. for Exp -

   String aa = "text";
   String bb = "text";

   if(aa == bb){
       System.out.println("yes");
   } else {
       System.out.println("No");
   }

will print - Yes

but
Line s = new line ("text"); Always create a new memory location and return a new link each time. for Exp -

   String aa = new String ("text");
   String bb = new String ("text");

   if(aa == bb){
       System.out.println("yes");
   } else {
       System.out.println("No");
   }

will print - No

+1
source

All Articles