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

5
  • Don't compare strings like that. stackoverflow.com/questions/513832/… Commented Sep 11, 2018 at 11:18
  • that's a referential comparison, don't expect it to behave like a comparison of values Commented Sep 11, 2018 at 11:19
  • Ya, but want to know how the results are obtained. Commented Sep 11, 2018 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. Commented Sep 11, 2018 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 Commented Sep 11, 2018 at 12:01

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Specifically, "Chai"+"pau" is a compile-time constant: "Constant expressions of type String are always "interned" so as to share unique instances"
Cool, as declaring final String b = "pau"; leaves the variable b to a compile time expression and the second case results to true.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.