Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between String s = "something"; and String s = new String("something"); [duplicate]

Tags:

java

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?

like image 711
CaiNiaoCoder Avatar asked Dec 04 '22 19:12

CaiNiaoCoder


2 Answers

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.

like image 184
Oliver Charlesworth Avatar answered Dec 22 '22 00:12

Oliver Charlesworth


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
like image 37
mishadoff Avatar answered Dec 22 '22 01:12

mishadoff