• Post Reply Bookmark Topic Watch Topic
  • New Topic

Why can't we use variables inside a case in switch construct?  RSS feed

 
radha gogia
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If I have an integer variable like int a=9 then in the switch case If i write
switch(a)
{
case 4+a: System.out.println("hii");

}

then why is this statement a compile-time error that variables cannot be used inside a case statement why does the compiler not subtitutes the values in place of the variables.

So basically what problem it creates for which the language developers did not include it as a proper syntax,is there any reason behimd this because of jump table?

 
Campbell Ritchie
Marshal
Posts: 56546
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because the values of the cases are worked out by the compiler. The method (in bytecode) is a choice table. The values must be known to the compiler, so they must be compile time constants. You can read about them in the Java® Language Specification, where they have the official name of constant expressions.
You may be able to correct that compiler error by marking some of those variable final.
 
Campbell Ritchie
Marshal
Posts: 56546
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No, you can't mark a final. Nor can you make it into a constant expression.
 
radha gogia
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
But why does the compiler not subtitute the value of the variables ,because it is a usual tendency of the compiler that wherever in my code I use a=a+9,then there the value of the variable would be subtituted then why not here the value of the variable subtituted ,what is the problem?
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The values have to be compile-time constants - the values must be known and fixed at compile time. The value of variables in general isn't known at compile time.

Why they have to be compile-time constants: that's what Campbell already tried to explain, it has to do with how the compiler translates this to bytecode. It creates a table in which the JVM can lookup where to go, depending of the value you're switching on. That table is fixed, that's why the values have to be compile-time constants. It's implemented this way because of efficiency reasons.

If you need to do different things depending of a variable instead of a constant value, use an if-statement (or a series of if-else if-else statements).
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!