-6

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??

1 Answers1

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