Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the string pool optimization defined by Java? [duplicate]

Tags:

java

standards

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.

like image 446
user7434748 Avatar asked Jul 26 '26 16:07

user7434748


2 Answers

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.

like image 148
user207421 Avatar answered Jul 28 '26 05:07

user207421


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

like image 26
vikingsteve Avatar answered Jul 28 '26 07:07

vikingsteve



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!