4

Possible Duplicate:
difference between string object and string literal

When initializing a String object there are at least two ways, like such:

String s = "some string";
String s = new String("some string");

What's the difference?

Community
  • 1
  • 1
CaiNiaoCoder
  • 3,269
  • 9
  • 52
  • 82
  • 3
    See this: [difference between string object and string literal](http://stackoverflow.com/questions/3297867/difference-between-string-object-and-string-literal) – Jon Lin Nov 08 '11 at 11:11
  • 1
    Duplicate of : http://stackoverflow.com/q/3297867/977676 – COD3BOY Nov 08 '11 at 11:18

4 Answers4

8

The Java language has special handling for strings; a string literal automatically becomes a String object.

So in the first case, you're initializing the reference s to that String object.

In the second case, you're creating a new String object, passing in a reference to the original String object as a constructor parameter. In other words, you're creating a copy. The reference s is then initialized to refer to that copy.

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
7

In first case you can take this string from pool if it exist there. In second case you explicitly create new string object.

You can check this by these lines:

String s1 = "blahblah";
String s2 = "blahblah";
String s3 = new String("blahblah");
String s4 = s3.intern();
System.out.println(s1 == s2);
System.out.println(s1 == s3);
System.out.println(s2 == s3);
System.out.println(s1 == s4);

Output:
true
false
false
true
mishadoff
  • 10,719
  • 2
  • 33
  • 55
1

String s = "some string"; assigns that value to s from string pool (perm.gen.space) (creates one if it does not exist)

String s = new String("some string"); creates a new string with value given in constructor, memory allocated in heap

The first method is recommended as it will help to reuse the literal from string pool

Anish Dasappan
  • 415
  • 2
  • 9
0

Semantically, the first one assigns "some string" to s, while the second one assigns a copy of "some string" to s (since "some string" is already a String). I see no practical reasons to do this in 99.9% of cases, thus I would say that in most contexts, the only difference between the two lines is that:

  1. The second line is longer.
  2. The second line might consume more memory than the first one.
  3. As @Anish-Dasappan mentions, the second one will have it's value in heap, whereas the first one will be in the string pool - I'm not sure this has any interest for the programmer, but I might be missing a clever trick there.
Romain
  • 12,679
  • 3
  • 41
  • 54