5

Consider this code:

int num = 0;

switch(num) {
   case 1:
      boolean bool = false;
      break;
   case 2:
      String one;
      String two;
      String three;
      //..simulating lots of vars
      break;
   default:
      bool = true;
      System.out.println(bool);
      break;
}

Since we were allowed to reference a variable declared in another case, this means that even though case 1 wasn't chosen, boolean bool was still declared.

Since default is the last option, and java works from left to right (top to bottom), I'm assuming that the variables in case 2 (and any other cases) will also be declared.

This make me think that the more code you have in the cases declared before the case chosen, the longer it'll take to actually access that case compared to if the chosen case was declared first.

Is there a specific reason switch statements work this way? And wouldn't it be best to use if-else rather than switch statements if there are a lot of cases? (talking processing time, nano-seconds)

Vince
  • 14,470
  • 7
  • 39
  • 84
  • 6
    Design decision. Simplifies fall through cases. Add `{}` to scope cases. – Boris the Spider Oct 14 '14 at 04:42
  • 1
    `switch (...) { all cases belong to this context }`, then you could also use `case ...: { this case now has own context }` ;) – MadProgrammer Oct 14 '14 at 04:42
  • 1
    "Optimization" does not apply here. Either construct could have been implemented just as efficiently. The byte-code / VM simply doesn't care about local variables as programmers do. (ie. Java does not "execute" variable declarations.) – user2864740 Oct 14 '14 at 04:43
  • 1
    If you have enough cases in your switch to make a difference in running time, something has gone dreadfully wrong. However, switches will in general be faster than an if chain, since they compile to well-made lookup tables, and are not evaluated as a sequence of decisions. (this is why you can't switch on comparisons, but only on values) – Jon Kiparsky Oct 14 '14 at 04:45
  • In C it allows [Duff's device](http://en.wikipedia.org/wiki/Duff%27s_device). But, that's not really an argument either way. – Elliott Frisch Oct 14 '14 at 04:47
  • "the more code you have in the cases declared before the case chosen, the longer it'll take to actually access that case": Why? The number of variables declared does not make a difference in the run time. – Henry Oct 14 '14 at 04:50
  • 1
    please refer http://stackoverflow.com/questions/3894119/variables-scope-in-a-switch-case – DeepInJava Oct 14 '14 at 04:50
  • 1
    @JonKiparsky It's more about how many variables are declared before your case is chosen rather than the number of cases – Vince Oct 14 '14 at 04:51
  • 1
    @SanketPipariya I understand the scope; what I didn't understand was why, due to the concerns listed in my question – Vince Oct 14 '14 at 04:53
  • @VinceEmigh If you have enough of ANYTHING in a switch to make a difference to running time, something has gone very wrong. Really, if you have a switch in a Java program at all, that's already pretty strong code smell... – Jon Kiparsky Oct 14 '14 at 04:55
  • @JonKiparsky I understand the concept of replacing switch statements with polymorphism, this was just something that caught my eye, and it didn't make sense as to why it would be that way instead of each case having its own scope. It came up while rewriting some older code – Vince Oct 14 '14 at 05:00

2 Answers2

3

{ } represents a scope and you could use it in any way you like.

In a switch statement:

switch (...) {
}

Everything inside the { } belongs in the same scope. If you want to have the cases have their own scope, you need to use { } like this:

switch (...) {
    case 0: {
    }
    break;
    case 1: {
    }
    break;
}

Similarly, you can use { } do declare scopes within scopes like this:

{
      {
          int i;
      }
      {
          int i;
      }
}
gmarintes
  • 1,288
  • 12
  • 16
  • I understand how scopes work. I was wondering why switch statements were designed this way, rather than each case having its own scope, so this doesn't answer my question (sorry) – Vince Oct 14 '14 at 05:03
  • 1
    I did not design java so I can't be sure, but my guess is that the switch statement needs a { }, and to be consistent with '{ }' representing a scope, they needed to make it behave this way. Consider the if-statement. It does not require { }, BUT it also does not allow you to declare variables without using { }: if (true) int x = 0; throws a syntax error. – gmarintes Oct 14 '14 at 05:05
  • 1
    @VinceEmigh - you can easily *add* extra scopes inside the `case`s, if that's what you want to do (as illustrated here). But if the java language *forced* extra scopes for each `case` and you actually *wanted* multiple `case`s to share a scope, how would you do that? That is, as the language is, you can implement either semantic (but one requires additional typing `{}`s). – Damien_The_Unbeliever Oct 14 '14 at 06:10
2

Switch statements in Java were patterned after switch statements in C++ were patterned after switch statements in C were probably patterned after switch statements in B ... BCPL (which certainly has the same single-block structure) ...

As a long lost Sun bug report says (about something else), 'the reasons are lost in the mists of time'.

user207421
  • 305,947
  • 44
  • 307
  • 483