0
public class SwitchTest {

public static void main(String[] args) {
    Integer i = new Integer(2) + new Integer(2);

    switch(i){
      case 4: System.out.println("foo"); break;
      default: System.out.println("default"); break;
    }
  }
}

Integer i is not marked as final. (I'm only a beginner in java.)

Codistan
  • 1,469
  • 1
  • 13
  • 17
  • `i` isn't a "switch constant" here, it's the variable being switched on. It'll switch on the current value, just like an `if`. – lmm Dec 23 '14 at 15:01
  • Switch parameters do not have to be final. something is not correct in your environment. – Rami Del Toro Dec 23 '14 at 15:03
  • 1
    You can also write: `switch(new Random().nextInt())` without any problem. But you cannot write `case new Random().nextInt():`, because each `case` needs a *compile-time constant*. – Tom Dec 23 '14 at 15:04

1 Answers1

3

You're confusing case labels with switch operands.

There is nothing wrong with switching on a non-constant value; in fact, without that, switch would be mostly useless.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964