0

In the following code a string is created in pool and then it is concat creating there additional string object. The final is "2cfalse" and is referred by a. Then in line 7, because of Strings' non-repeating nature, I think it does not create separate literal as "2cfalse" so the == operator must return true .. Why its not returning true..

class demo {
    public static void main(String aaa[]) {
        String a = "";
        a += 2;
        a += 'c';
        a += false;
        if (a == "2cfalse")
            System.out.println(1);
        if (a.equals("2cfalse"))
            System.out.println(2);
    }
}
Ben
  • 1,414
  • 2
  • 13
  • 18
  • 9
    http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java – Reimeus Feb 18 '16 at 14:33
  • The compiler will for `+=` (or smiply `+`) on Strings create a StringBuilder behind the scene, and use its `.append()`-method ([source](http://stackoverflow.com/a/11408526/1682559)). So with every `+=` you actually create a new String-object that also need to be garbage collected. Which is why we got classes like `StringBuilder` for appending Strings. So in your check `if (a == "2cfalse")` they aren't referencing to the same String-object. – Kevin Cruijssen Feb 18 '16 at 14:43
  • Your code a += 2 is equivalent to String s = new StringBuffer().append(a).append("2"), So you have to s.intern() in order for == to work, your question is probably linked to wrong question – awsome Feb 18 '16 at 14:44
  • Thank you guys. this is the answer i was expecting. – Saksham Mahendru Feb 19 '16 at 11:22

1 Answers1

1

This is because == compares Strings by their memory location vs String.equals which compares them lexicographically.

Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132