1

I have two java snippets using a constant in a switch case:

final Integer s1=5;
int x=5;
switch(x){
    case s1:  **<== causes complilation error..**
        System.out.println("hello");
}

The code below works fine as s1 is treated as a constant, whereas the code above does not work.

final int s1=5;
int x=5;
switch(x){
    case s1: <=== ok s1 is constant
        System.out.println("hello");
}

What is the difference between the above two declarations?

ntalbs
  • 28,700
  • 8
  • 66
  • 83
dead programmer
  • 4,223
  • 9
  • 46
  • 77
  • Very close, but not quite a duplicate: http://stackoverflow.com/questions/4401743/why-final-static-int-can-be-used-as-a-switchs-case-constant-but-not-final-st (Answer applies here, too) – Thilo Dec 18 '14 at 04:07
  • i don't understand what the question is. OK, you've seen that one of these works and the other doesn't. You know what the difference is between them. What are you asking, exactly? – Dawood ibn Kareem Dec 18 '14 at 04:08
  • 1
    http://www.coderanch.com/t/329474/java/java/final-static-Integer-considered-constant – Thilo Dec 18 '14 at 04:09
  • Another very similar question: http://stackoverflow.com/questions/15309692/difference-between-final-variables-and-compile-time-constant?rq=1 – Thilo Dec 18 '14 at 04:12
  • 1
    @DavidWallace I think it's a reasonable question. He's asking why a final Integer cannot be treated as a constant expression in a switch statement. I guess the answer is that the language designers could easily have made this work, but it would have complicated the definition of a constant expression, for no good reason. – Paul Boddington Dec 18 '14 at 04:19
  • 1
    @pbabcdefp OK. So it's a "why did the designers do this" question. I understand now. Personally, I dislike such questions, because in most cases, they can only be answered by the designers of Java; and I'm not sure if any of them actually hang out on Stack Overflow. But the fact that nobody here can possibly answer it doesn't make it an unreasonable question, I agree. I find it amusing that two people have already tried, and no doubt more will follow. – Dawood ibn Kareem Dec 18 '14 at 04:47

2 Answers2

3

The Java Language Specification defines:

SwitchLabel:

  • case ConstantExpression :
  • case EnumConstantName :
  • default :

That is, a case label must either be the name of an enum constant, or a ConstantExpression. The spec also says:

A constant expression is an expression denoting a value of primitive type or a String that does not complete abruptly and is composed using only the following:

That is, an Integer is not a compile type constant expression, and therefore can not be used as a case label.

Community
  • 1
  • 1
meriton
  • 68,356
  • 14
  • 108
  • 175
2

switch statements only work on primitive types and Strings and enums. An Integer is neither a primitive type nor a String or enum, so it gives a compile error.

tckmn
  • 57,719
  • 27
  • 114
  • 156