2

I am trying to understand how this is valid in case statement of a switch in Java.

switch(someValue){
    case abc: int i=0
    break;
    case def: int i=0 // error because i declared above is still accessible in this case.`

If we say that variables have a block scope in Java , shouldn't the "i" variable be inaccessible in the case of def? Or is the case not treated as a block ? Many people must have come across this problem before.

Why does this not violate any fundamental concepts of programming?

TNT
  • 2,900
  • 3
  • 23
  • 34
user1079065
  • 2,085
  • 9
  • 30
  • 53

1 Answers1

4

Because the block is what follows the switch statement, not each case within it:

switch (...) { // start of block
  case: ...
  break;
  ...
} // end of block

Writing break doesn't put an end to the block when it's used in a for loop; likewise, writing case doesn't begin a new block when it's used in a switch. It might help to think of them as labels to jump to within the block.

If you want to reuse the variable, you might define it within a block after your case:

case abc: {int i=0 ...}
  break;
mk.
  • 11,360
  • 6
  • 40
  • 54