Directly initialized final field is not constant folded later when prefix with "this"

Alex Buckley alex.buckley at oracle.com
Thu Jun 11 17:53:54 UTC 2020


On 6/11/2020 10:08 AM, Christoph Dreis wrote:
> Today I experimented around with constant folding and created the following class:
> 
> 	private final String world = "world";
> 
> 	public String world() {
> 		return "Hello " + "world";
> 	}
> 
> 	public String worldField() {
> 		return "Hello " + world;
> 	}
> 
> 	public String worldFieldThis() {
> 		// This is not constant folded
> 		return "Hello " + this.world;
> 	}
...
>    public java.lang.String worldField();
>      Code:
>         0: ldc           #14                 // String Hello world
>         2: areturn
> 
>    public java.lang.String worldFieldThis();
>      Code:
>         0: aload_0
>         1: invokestatic  #16                 // Method java/util/Objects.requireNonNull:(Ljava/lang/Object;)Ljava/lang/Object;
>         4: pop
>         5: ldc           #7                  // String world
>         7: invokedynamic #22,  0             // InvokeDynamic #0:makeConcatWithConstants:(Ljava/lang/String;)Ljava/lang/String;
>        12: areturn
> 
> I would have expected to actually see things in worldFieldThis to be constant folded as well.
> Especially since the field is initialized directly and not anywhere else (e.g. in the constructor).
> Why is "this" making a difference here?

`this.world` is not a constant expression. String interning is driven by 
the rules of constant expressions, which are set up for predictability 
in all scenarios not just string concat/interning.

Alex


More information about the compiler-dev mailing list