if you write String s = new String ("abc"); two objects get created on is in non pool (heap) area and one is in common String pool (if it not exists. ) Suppose it creates two objects. Now when I create String literal String s1 ="abc"; Now according to me in string pool there is one string "abc" and has two reference s1 and s. so System.out.println(s==s1) it should give true but its giving false.. why??
Asked
Active
Viewed 78 times
-6
-
cmon dude , have u seen the statement ,its entirely different from what u ve marked :/ – Nasir Ul Islam Butt Jun 29 '14 at 20:12
-
1`s` does not refer to `"abc"` but to `new String("abc")`. You intentionally create a new `String` object. You should never use the `String(String)` constructor because it clutters your memory. – Tobias Jun 29 '14 at 20:13
-
1Look at the accepted answer to the question. It mentions your case. – BitNinja Jun 29 '14 at 20:13
-
`s` is a new object you created which is not in the String literal pool. – Peter Lawrey Jun 29 '14 at 20:17
1 Answers
1
The part which might be identical for both of your Strings is their backing char[]
array value and therefore s.equals(s1)
. But any objects created with separate constructor calls are not identical objects. And as your s and s1 are constructed separately (one by compiler, the other during runtime) therefore s != s2
.
Try the following example, there compiler uses the same object for both of the strings (although they are declared separately) and therefore s == s1 will be true:
public static void main(String[] args) {
String s = "abc";
String s1 = "abc";
System.out.println(s == s1);
}

Vladimír Schäfer
- 15,375
- 2
- 51
- 71