Declarations do not run - they are not what you need to execute, they just tell the compiler the type of the variable. (The initializer will work, but that's fine - you are not trying to read from the variable before assigning it a value.)
The accumulation inside switch statements is definitely odd, but basically the variable declared in the first case is still in scope in the second case .
From section 6.3 JLS :
The declaration volume of a local variable in a block (ยง14.4) is the rest of the block in which the declaration appears, starting with its own initializer and including any other declarators on the right in the statement for declaring the local variable.
If you do not create additional blocks, the entire switch statement will be a single block. If you want to create a new area for each case, you can use curly braces:
case 1: { int y = 7; ... } case 2: { int y = 5; ... }
source share