-2

Java Question: Suppose str is a String variable. The statement str = new String("Hello World"); is equivalent to ?

Here are my choices...

a.

new String = "Hello World"; 

c.

str = "Hello World";

b.

String new = "Hello World";

d.

"Hello World";
user2805478
  • 9
  • 1
  • 5
  • [link1](http://stackoverflow.com/questions/6191086/whats-the-difference-between-string-and-new-string) - [link2](http://stackoverflow.com/questions/6952581/what-is-the-difference-between-strings-allocated-using-new-operator-without-ne) – Husam Sep 23 '13 at 01:35
  • Is equivalent to create pottentionally 2 strings.. "Hello World" if it doesn't exist in the "pool" and a new allocation with the same value. – nachokk Sep 23 '13 at 01:36
  • @nachokk The literal *does* exist in the pool: it is put there by the compiler. – user207421 Sep 23 '13 at 01:39

2 Answers2

6

It's equivalent to declaring and initializing it at once:

String str = new String("Hello World");

You don't need to do new String("...") though. You already have a String literal. You can just do:

String str = "Hello World";

Otherwise, you're taking the first, canonical String object ("Hello World") and unnecessarily using it to initialize a second object (new String(...)) with the same text.

Edit: According to the choices you've posted now, it's not exactly equivalent to any of them. As explained in more detail by the other answers, "Hello World" has a subtle (yet important) difference to new String("Hello World"), so it is not exactly equivalent to str = "Hello World". On the other hand, the other three options don't compile at all, so that is certainly the intended answer.

Boann
  • 48,794
  • 16
  • 117
  • 146
2

Lots of answer get it right about internalization. Take this program:

public static void main(String[] args) {
    String str1 = "Hello";
    String str2 = "Hello";
    String str3 = new String("Hello");
    String str4 = "He";
    System.out.println(str1 == str2);  // true

    System.out.println(str1 == str3);  // false

    System.out.println(str1 == str3.intern());  // true

    str4 = str4.concat("llo");
    System.out.println(str1 == str4.intern());  // true

}

The interesting issues are point 2 and 3. new always creates a new object (as per JLS 12.5), so str1 != str3. What happens with internalization is that the new object points to the internalized one, which you can retrieve with String.intern(). Similarly, another String created in a form completely unrelated to the original literals (str4) also gets "interned".

SJuan76
  • 24,532
  • 6
  • 47
  • 87