Is Java guaranteed to inline string constants if they can be determined at compile time

It’s guaranteed to be treated as a constant expression, and guaranteed to be interned by section 15.28 of the JLS:

A compile-time constant expression is
an expression denoting a value of
primitive type or a String that does
not complete abruptly and is composed
using only the following:

  • Literals of primitive type and literals of type String (§3.10.5)
  • Casts to primitive types and casts to type String
  • The unary operators +, -, ~, and ! (but not ++ or –)
  • The multiplicative operators *, /, and %
  • The additive operators + and –

Compile-time constants of type String
are always “interned” so as to share
unique instances, using the method
String.intern.

Now, that doesn’t quite say it’s guaranteed to be inlined. However, section 13.1 of the spec says:

References to fields that are constant
variables (§4.12.4) are resolved at
compile time to the constant value
that is denoted. No reference to such
a constant field should be present in
the code in a binary file (except in
the class or interface containing the
constant field, which will have code
to initialize it), and such constant
fields must always appear to have been
initialized; the default initial value
for the type of such a field must
never be observed.

In other words, even if the expression itself weren’t a constant, there should be no reference to Class1. So yes, you’re okay. That doesn’t necessarily guarantee that the concatenated value is used in the bytecode, but the bits referenced earlier guarantee that the concatenated value is interned, so I’d be hugely surprised if it didn’t just inline the concatenated value. Even if it doesn’t, you’re guaranteed that it’ll work without Class1.

Leave a Comment