3

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.

  • 1
    In your example, yes. You use [string literals](http://stackoverflow.com/questions/3297867/difference-between-string-object-and-string-literal) which java will pool as one using [String interning](https://en.wikipedia.org/wiki/String_interning). It won't work if you create string objects, which can happen easily, so the job interview answer should contain that while this works in this case, it is unsafe to do, because you might copy the code to a place where it doesn't work. – Aziuth Jan 18 '17 at 09:34
  • 1
    Saw some comment of yours that you deleted about you answering no in the interview, in regard to that: So, you don't know every single detail about java? And you tend to go for the save solution instead of taking a risky guess? Sounds reasonable. The ability to learn is far more important than some detail. Although a better answer would have been to say something like "I don't think so, but I'm not sure about that.". At least if the interviewer is smart. Mistakes happen and being aware that you are not immune to mistakes is important. In conclusion, don't take it too hard. – Aziuth Jan 18 '17 at 09:55

2 Answers2

3

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 method String.intern.

user207421
  • 305,947
  • 44
  • 307
  • 483
3

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

vikingsteve
  • 38,481
  • 23
  • 112
  • 156