final int a=2;
final int b;
b=3;
switch(num){
case a : // Legal
case b : //Illegal
}
case a is Legal but case b is Illegal.
Can anyone explain why?
final int a=2;
final int b;
b=3;
switch(num){
case a : // Legal
case b : //Illegal
}
case a is Legal but case b is Illegal.
Can anyone explain why?
switch
statement requires constant expression case labels.
While b
is a constant after the code executed (so the final
works), it is not a constant expression in the meaning of JLS : https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.28