4

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?

Community
  • 1
  • 1
Jackson Tale
  • 25,428
  • 34
  • 149
  • 271
  • same question applies for `new Boolean(true)` when you can do `Boolean.TRUE`. – Thilo May 31 '12 at 08:14
  • There are lots of trivial pieces of code that you wouldn't expect Java to *prevent* you from writing. `int a = 5 + 1 - 1;` is silly, but legal. – Damien_The_Unbeliever May 31 '12 at 08:16
  • 1
    @Damien_The_Unbeliever: That particular example is taken care of by the compiler (whereas `new String("s");`) is not. – Thilo May 31 '12 at 08:17
  • @Thilo - that's could be argued a point in *favour* of allowing such constructs (as opposed to the OPs position of wanting Java to outlaw perfectly legal expressions). – Damien_The_Unbeliever May 31 '12 at 08:19

1 Answers1

1

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 -

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

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

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 -

   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

Pramod Kumar
  • 7,914
  • 5
  • 28
  • 37
  • sorry, can you give a specific example of when I should use new string then? I know the theory behind it, just lack of example – Jackson Tale May 31 '12 at 08:33