Is there any way I can get the expression below to evaluate as a constant expression? I am using Java 11 if that helps.
String.format("hello %1$s","world");
Is there any way I can get the expression below to evaluate as a constant expression? I am using Java 11 if that helps.
String.format("hello %1$s","world");
No, the compiler cannot treat this as compile-time constant expression (Also see this question).
To illustrate: Using bytecode manipulation, it would be possible to modify the behavior of String.format(), e.g. what is possible in unit-testing with PowerMock and similar libraries. In that case String.format("hello %1$s","world")
could return something else than "hello world".
Note:
I assume you mean as a "compile-time constant expression". (Else you can just define a variable final foo = String.format(...)
, and the variable foo will be a constant in the following code). But such constants cannot e.g. be used as annotation values.