5

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");
Nosrep
  • 521
  • 7
  • 21
abhaybhatia
  • 599
  • 1
  • 7
  • 16
  • Do you mean you want the string "hello world" to be treated as a constant? It's not a constant, it's being interpolated at runtime. – Dave Newton May 21 '19 at 23:46
  • 1
    @DaveNewton I want to achieve this functionality at compile time ( and am not bound to String.format api). One way I know of achieving this is String x = "world"; String y = "Hello" + x; ... Here y is a constant though it uses a variable. I don't want to use this approach though since I have a lot of variables to replace and was hoping for a different solution. – abhaybhatia May 21 '19 at 23:57
  • 2
    What’s the ultimate problem you’re trying to solve? – Dave Newton May 22 '19 at 00:18
  • Possible duplicate of [Compile-time constants and variables](https://stackoverflow.com/questions/9082971/compile-time-constants-and-variables) – tkruse May 22 '19 at 01:22
  • Currently not, but see https://openjdk.java.net/jeps/348 for a potential improvementon this. – Petr Janeček Jun 19 '20 at 09:07
  • @DaveNewton Should not matter. – Aakash Verma Sep 20 '21 at 14:20
  • @AakashVerma And yet it does--if, say, the ultimate problem is doing some string replacement, this might be handled by a Maven/Gradle plugin (e.g., property file replacements). If the issue is needing string constants in a byteclass file then any of several bytecode modification tools could be used. If the issue is creating a runtime constant at runtime, then it's not possible. – Dave Newton Sep 20 '21 at 15:04

1 Answers1

5

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.

tkruse
  • 10,222
  • 7
  • 53
  • 80