Codistan
Codistan

Reputation: 1519

How can non-final variables be switch constants?

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.)

Upvotes: 0

Views: 434

Answers (1)

SLaks
SLaks

Reputation: 887887

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.

Upvotes: 3

Related Questions