-3

How does Java implement the below string comparisons

public class MyClass {
    public static void main(String args[]) {
        String a = "Chaipau";
        String b = "pau";

        System.out.println(a == "Chai"+"pau"); //true
        System.out.println(a == "Chai"+b); //false
    }
}

This is different from How do I compare strings in Java? , as the answer does not contain the why a new object is created in the second case , when it could have pointed to the same object reference as it is done in the first case.

Chaipau
  • 199
  • 1
  • 5
  • 14
  • Don't compare strings like that. https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java – Worthless Sep 11 '18 at 11:18
  • that's a referential comparison, don't expect it to behave like a comparison of values – Stultuske Sep 11 '18 at 11:19
  • Ya, but want to know how the results are obtained. – Chaipau Sep 11 '18 at 11:20
  • The == compares references, so the "numbers" that identify the two memory areas occupied by the objects. It is a 32 or 64 bit value depending on platform. In conclusion, the result is non deterministic, because it depends on memory actual state; that's the reason because == should not be used when comparing non-primitive types. – Andrea Sep 11 '18 at 11:24
  • the first one is a constant and it is interned in the string constant pool, thus two references point to the same thing in the constant pool. the second one is not a constant, but you try to reference it from the constant pool, thus false – Eugene Sep 11 '18 at 12:01

1 Answers1

5

"Chai"+"pau" is semantically identical to "Chaipau", and thus is the same instance that a refers to.

"Chai"+b is evaluated at runtime (because b is not a compile-time constant expression), creating a new instance of String, and thus is not the same instance that a refers to.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
  • Specifically, `"Chai"+"pau"` is a [compile-time constant](https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.28): "Constant expressions of type String are always "interned" so as to share unique instances" – Michael Sep 11 '18 at 11:29
  • 1
    Cool, as declaring final String b = "pau"; leaves the variable b to a compile time expression and the second case results to true. – Chaipau Sep 11 '18 at 11:29