Guifan Li Guifan Li - 16 days ago 6
Java Question

JVM architecture: Runtime constant pool in Method area is per-class

By reading Oracle JVM architecture document:

https://docs.oracle.com/javase/specs/jvms/se7/html/jvms-2.html


A run-time constant pool is a per-class or per-interface run-time
representation of the constant_pool table in a class file (§4.4).


I understand that for each class, it has a runtime constant pool (please correct me if I am wrong).

However, what I am confused is that if I have two different classes A and B and each class has a private String variable say
String value = "abc"
.

if I compare
A.value
with
B.value
using
==
rather than
equals
, I will get a
true
which make me think that
"abc"
in both A and B are in the same runtime constant pool? Could someone point me out where I am wrong ?

Answer

This is a preemptive optimization that the JLS superimposes.

From JLS 7, §3.10.5 (formatting mine)

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.

However, note that this is only true of String literals and constant expressions. Dynamically constructed strings (e.g. x + y for Strings x and y) are not automatically interned to share the same unique instances. As a result, you will still have to use .equals in general unless you can guarantee that your operands are constant expressions.

Comments