Is a == b always true in all Java fully-compatible implementations?
String a = "abc";
String b = "abc";
if (a == b)
System.out.println("True");
I was asked if True will be printed in a job interview. I was aware of that a and b could point to the same "abc" as an optimization, but I was not sure if this optimization is standardized or it is jut a particular implementation behavior.
Yes. It is guaranteed by the Java Language Specification #3.10.5:
Moreover, a string literal always refers to the same instance of class
String. This is because string literals - or, more generally, strings that are the values of constant expressions (§15.28) - are "interned" so as to share unique instances, using the methodString.intern.
The interning of string literals is specified in the java language specification, JLS section 3.10.5.
See: Moreover, a string literal always refers to the same instance of class String. This is because string literals - or, more generally, strings that are the values of constant expressions (§15.28) - are "interned" so as to share unique instances, using the method String.intern
So yes, the correct answer for your job interview would be "yes", but you should certainly follow up and say that String equivalence should always be tested via .equals().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With