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

Roland Illig roland.illig at gmx.de
Thu Jun 11 19:18:57 UTC 2020


On 11.06.2020 19:53, Alex Buckley wrote:
> 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 worldField() {
>>         return "Hello " + world;
>>     }
>>
>>     public String worldFieldThis() {
>>         // This is not constant folded
>>         return "Hello " + this.world;
>>     }
>
> `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.

I had thought that `world` were semantically the same as `this.world`,
but JLS 14 says in "15.29 Constant Expressions":

 > A constant expression is ...
 >
 > *  Simple names (§6.5.6.1) that refer to constant variables
 >    (§4.12.4).
 >
 > *  Qualified names (§6.5.6.2) of the form TypeName.Identifier
 >    that refer to constant variables (§4.12.4).

I wouldn't have expected that this makes a difference, but since `this`
is not a TypeName, the compiler works as specified.

This leaves the question why `this.field` was not defined to be
equivalent to the unqualified `field` in the first place? Can anyone
shed a light on this?

Roland


More information about the compiler-dev mailing list