1
        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?

sha sha
  • 115
  • 9
  • 3
    You can't reassign a final variable. Either assign a number to b or make it NOT final. – Igor Flakiewicz Sep 03 '21 at 19:05
  • 1
    What is the compile error here? – Nathan Hughes Sep 03 '21 at 19:06
  • 1
    You can only reassign final variables in a constructor. https://stackoverflow.com/a/11345841/12302982 – Igor Flakiewicz Sep 03 '21 at 19:07
  • @IgorFlakiewicz - Please provide a reference to your statement. – PM 77-1 Sep 03 '21 at 19:10
  • 5
    Notice that `b` is not initialized. We aren't changing its value in `b=3` - it's the initialization. And this is legal. Problem here is that the `switch` does not know about that. Roughly it requires labels to look like `final x = ....`. – Adam Kotwasinski Sep 03 '21 at 19:10
  • 4
    Found a link to a decent older answer https://stackoverflow.com/a/3827424/12302982 – Igor Flakiewicz Sep 03 '21 at 19:12
  • 3
    Reassigning local variables when they are `final` is indeed illegal. But the thing is that `b` is not reassigned – it is only assigned. [Here is an example](https://ideone.com/gCSOXt) which shows that using separate statements for *declaring* a `final` variable and *assigning* it, is perfectly fine. – MC Emperor Sep 03 '21 at 19:17
  • My Eclipse does not complaint about the assignment to `b`. It does complaint about using `b` as case label: *case expressions must be constant expressions*. – Ole V.V. Sep 03 '21 at 19:18
  • So it kind of seems like this is a case of the compiler showing it's very focused nature. It only checks to see if the value is initialized in the same line to determine it as a constant. It won't check other lines to see if it's a constant _eventually_ since that might require checking hundreds of lines of code before it could do a check on this value. That would be a potentially time intense operation. – Tim Hunter Sep 03 '21 at 19:23

1 Answers1

6

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

Adam Kotwasinski
  • 4,377
  • 3
  • 17
  • 40