Guifan Li Guifan Li - 1 year ago 85
Java Question

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

By reading Oracle JVM architecture document:

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
rather than
, I will get a
which make me think that
in both A and B are in the same runtime constant pool? Could someone point me out where I am wrong ?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download