Skip to content Skip to sidebar Skip to footer

A Switch Java Problem : Case Expressions Must Be Constant Expressions

I having a problem in my switch/case statement. The error says : 'Case expressions must be constant expressions'. I understand the error and I can resolve it using If but can someo

Solution 1:

So it can be evaluated during the compilation phase ( statically check )

See: http://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.11 for a formal definition of the switch.

Additionally it may help you to understand better how that switch is transformed into bytecode:

classSwitch {
  voidx(int n ) {
    switch( n ) {
      case1: System.out.println("one"); break;
      case9: System.out.println("nine"); break;
      default:  System.out.println("nothing"); break;
    }
  }
}

And after compiling:

C:\>javap -c Switch
Compiled from "Switch.java"
class Switch extends java.lang.Object{
Switch();
  Code:
   0:   aload_0
   1:   invokespecial   #1; //Method java/lang/Object."<init>":()V4:   return

void x(int);
  Code:
   0:   iload_1
   1:   lookupswitch{ //21: 28;
                9: 39;
                default: 50 }
   28:  getstatic       #2; //Field java/lang/System.out:Ljava/io/PrintStream;31:  ldc     #3; //String one33:  invokevirtual   #4; //Method java/io/PrintStream.println:(Ljava/lang/String;)V36:  goto    5839:  getstatic       #2; //Field java/lang/System.out:Ljava/io/PrintStream;42:  ldc     #5; //String nine44:  invokevirtual   #4; //Method java/io/PrintStream.println:(Ljava/lang/String;)V47:  goto    5850:  getstatic       #2; //Field java/lang/System.out:Ljava/io/PrintStream;53:  ldc     #6; //String nothing55:  invokevirtual   #4; //Method java/io/PrintStream.println:(Ljava/lang/String;)V58:  return

}

See that line marked as 1:

1:   lookupswitch{ //21: 28;
            9: 39;
            default: 50 }

It evaluates the value and goes to some other line. For instance if value is 9 it will jump to instruction 39:

39:getstatic#2; //Field java/lang/System.out:Ljava/io/PrintStream;42:ldc#5; //String nine44:invokevirtual#4; //Method java/io/PrintStream.println:(Ljava/lang/String;)V47:goto58

Which in turn jumps to instruction 58 :

58:  return

All this wouldn't be possible if it was evaluated dynamically. That's why.

Solution 2:

in eclipse IDE is simple ,in switch sentence CTRL + 1 and convert switch sentence - if-else sentence http://tools.android.com/tips/non-constant-fields

Solution 3:

The idDirectory and others need to be a constant and not a declared variable. Switch will not work in this case, you need switch to if-else construct.

EDIT I see what OP meant. That is just how switch works in java language.

Post a Comment for "A Switch Java Problem : Case Expressions Must Be Constant Expressions"