Final variable initialization problem with exhaustive switch
Dimitris Paltatzidis
dcrystalmails at gmail.com
Wed Jan 12 20:35:17 UTC 2022
The file I have is: Main.java
public class Main {
public static void main(String[] args) {
enum Parity {ODD, EVEN}
Parity p = Math.random() > 0.5 ? Parity.EVEN : Parity.ODD; //or
whatever
final int a;
switch (p) {
case ODD -> a = 1;
case EVEN -> a = 0;
}
int b = a + 1;
}
}
Trying to compile it with (java -version):
openjdk version "17.0.1" 2021-10-19
OpenJDK Runtime Environment (build 17.0.1+12-39)
OpenJDK 64-Bit Server VM (build 17.0.1+12-39, mixed mode, sharing)
I get:
Main.java:11: error: variable a might not have been initialized
int b = a + 1;
^
1 error
I tried it in IntelliJ as well, and aside from the pre-compile warnings I
got, I still could not compile it.
Should I enable preview features to pass? I think I might have done that
too, but got the same results.
I'm confused. Suppose I'm doing something wrong, does that mean switch
statements can be total in JDK 17?
Στις Τετ 12 Ιαν 2022 στις 4:56 μ.μ., ο/η Brian Goetz <brian.goetz at oracle.com>
έγραψε:
> I'm not seeing this fail on JDK 17.
>
> On 11/29/2021 3:04 PM, Dimitris Paltatzidis wrote:
>
> Consider the case:
>
> enum Parity {ODD, EVEN}
> Parity p = ...
> final int a;
> switch (p) {
> case Parity.ODD -> a = 1;
> case Parity.EVEN -> a = 0;
> }
> int b = a + 1; //Compile time error: variable a might not have been
> initialized
>
> The switch is exhaustive, yet we need to add a default case to compile. The
> same behaviour is observed with instance final fields too.
> Without changing the semantics, the code below compiles:
>
> final int a = switch (p) {
> case Parity.ODD -> 1;
> case Parity.EVEN -> 0;
> };
> int b = a + 1; //Compiles
>
> How can the compiler prove that the final variable will be initialized only
> in the second case and not in the first too?
>
> Thanks for your time.
>
>
>
More information about the amber-dev
mailing list