Can switch expression be compile-time constant?

Maurizio Cimadamore maurizio.cimadamore at oracle.com
Thu Nov 22 13:50:38 UTC 2018


One small point, as I've recently discussed this with Jan.

Tagir, you are asking two questions :-)

1) Should a switch expression (of the right kind) be treated as a 
'constant expression' (as per 15.28) ?

2) Should javac opportunistically fold away dead code when it can detect so?

The answer to (1), as Brian says, is a deliberate 'no'; otherwise, you 
could have switch expression appearing after a 'case' too...

The answer to (2) is, well, javac *could*. But it's completely 
implementation-dependent as some optimization in the generated bytecode 
will take place or not.

That said, (2) is partially related to our efforts in JEP 303 - maybe 
there are cases in which it could make sense to treat certain switch 
expressions as 'trackable' by javac (which doesn't mean constant as per 
15.28!!), so that intrinsification can happen.

Maurizio

On 22/11/2018 13:03, Brian Goetz wrote:
> Yes, this was a deliberate choice.
>
> Sent from my iPad
>
>> On Nov 22, 2018, at 5:18 AM, Tagir Valeev <amaembo at gmail.com> wrote:
>>
>> Hello!
>>
>> It seems that switch expressions are not compiled as compile-time
>> constant (using Java12 ea builds). E.g.:
>>
>> public class Constant {
>>   public static void main(String[] args) {
>>     int x = switch(0) {case 1 -> 2; case 2 -> 3; default -> 1;};
>>     int y = 0 == 1 ? 2 : 0 == 2 ? 3 : 1;
>>     System.out.println(x);
>>   }
>> }
>>
>> The equivalent conditional expression is folded into constant 1, but
>> switch is present in bytecode as is. Is it deliberate decision to
>> exclude switches from compile-time constant?
>>
>> With best regards,
>> Tagir Valeev


More information about the amber-spec-experts mailing list