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?

2

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

Comments

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 

3 Comments

+1: You could add String s4 = s3.intern(); System.out.println(s1 == s4);
Sure, it will complete our example
thanks, you mentioned string pool. that's helpful, but I can only accept one as answer.
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

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.