Are all compile-time constants inlined?

You can use String.intern() to get the desired effect, but should comment your code, because not many people know about this. i.e.

public static final String configOption1 = "some option".intern();

This will prevent the compile time inline. Since it is referring to the exact same string that the compiler will place in the perm, you aren’t creating anything extra.

As an alternative you could always do

public static final String configOption1 = "some option".toString();

however this will not use the compiled intern’d string, it will create a new one on the old gen. Not a huge big deal, and might be easier to read. Either way, since this is a bit odd you should comment the code to inform those maintaining it what you are doing.

Edit:
Found another SO link that gives references to the JLS, for more information on this.
When to use intern() on String literals

Leave a Comment