-1

One of the roles for the switch statements is that they accept constants as arguments however observing the following code we can clearly notice a compilation error reported by the compiler at the marked line

public void testSwitch(final int y){
        final int x= 0;
        int tester = 9;
        switch(tester){
        case x:
            break;
        case y://compilation error here case constant must be constant expression
            break;
        }
    }

is this related to what is called "Compile time" constants?

A.Alqadomi
  • 1,529
  • 3
  • 25
  • 33
  • 1
    it is marked as final doesnt that make it a constant ?adding the following line would also make the compiler complain y=10; – A.Alqadomi Dec 22 '15 at 20:44
  • 1
    I think the problem is that `y` can change values between calls, so in that sense it's not a 'constant expression'. You need something there that will not change, even between calls. – code_dredd Dec 22 '15 at 20:47
  • 2
    y is not a constant expression since you can call with whatever value of y you want, repeatedly. – pvg Dec 22 '15 at 20:48
  • 3
    It's not a _compile time_ constant. – Louis Wasserman Dec 22 '15 at 20:51
  • @pvg damn, i was actually intrigued by this question until your link made me realize the value in the parameter was left off. now i just feel dumb. :( – Drew Kennedy Dec 22 '15 at 20:51
  • "is this related to what is called 'Compile time' constants?" -- yes, yes it is. – John Bollinger Dec 22 '15 at 20:51

1 Answers1

0

y parameter can have multiple values passed to the method call so it is not a constant. It could even be 0 value which would make it the same as case x

jonasnas
  • 3,540
  • 1
  • 23
  • 32