Case expressions must be constant expressions for static final int?

31,648

Solution 1

Replace

 case MorrisBoard.RING.OUT:

with

 case Ring.OUT:

So this will really be a constant as in "determined at compilation".

The specification precises that a "SwitchLabel" must be

  • case followed by a constant expression
  • case followed by the name of an enum value
  • or default

What is considered a valid constant expression is described here in the specification. It's fairly limited.

Solution 2

Simple solution for this problem is : Click on the switch and then press CTL+1, It will change your switch to if-else block statement, and will resolve your problem

Share:
31,648
Admin
Author by

Admin

Updated on March 23, 2020

Comments

  • Admin
    Admin over 4 years

    I have a final class Ring defined as:

    final class Ring {
        public static final int OUT = 3;
        public static final int MID = 2;
        public static final int IN  = 1;
    }
    

    I also have a public class MorrisBoard with the following code:

    public class MorrisBoard {
        public static final Ring RING = new Ring();
    
        private boolean checkMillBy(int ring, int x, int y) {
        switch(ring) {
        case MorrisBoard.RING.OUT:
            //...
        case MorrisBoard.RING.MID: //etc.
            //...   
        }
        return false;
    }
    

    MorrisBoard.RING.OUT references a variable which is immutable for the lifetime of the program. All values are final.

    However, I still get the following error: case expressions must be constant expressions. I'm confused by this - MorrisBoard.RING.OUT is a constant expression.

    What is going on here?

  • Hurda
    Hurda over 11 years
    Do you thing this will work when final class Ring is not static?
  • Admin
    Admin over 11 years
    In this particular case, it is, so this is an appropriate answer (thank you!). However, I would be curious to know how that would be handled.
  • Denys Séguret
    Denys Séguret over 11 years
    @Hurda If you can't refer to your externally defined constant simply with TypeName.Identifier, then it's not valid.
  • JGFMK
    JGFMK over 2 years
    BTW: This works for Spring Tool Suite - based on Eclipse IDE. Not sure if this works for IntelliJ or Netbeans the same way.