To prevent compile time inlining
The only use case I can think of is to prevent it from being considered as compile time constant, so that it prevents inlining.
Now one reason can be that someone can change the value using Reflection, which will only work if the string is declared like that.
Also it allows you to change the class file containing constant as told by @Duncan in his answer. That is a good reason too.
How does that work?
When you declare String
as public static final String CONST = "abc";
, then it is a compile time constant and will be inlined in the class using that constant.
class A{
private void foo(){
String newString = CONST + someDynamicValue;
}
}
After compiling this, if you decompile the class you will find
class A{
private void foo(){
String newString = "abc" + someDynamicString;
}
}
But when you declare it with .intern()
or any other method, then it cannot be considered as compile time constant and every time the value will be fetched from the class. Java does this to be efficient.
Example from @Marko's comment:
the SWT library uses a similar trick to stop from inlining int
constants, and the only reason is to be consistent with respect to
upgrading the SWT library