Scope in Switch Expression
Understand the Switch expression in Java, and its differences with if-else and for statements.
Join the DZone community and get the full member experience.
Join For FreeThe switch expression is not often used by Java developers in everyday practice. So, I suppose, knowledge about this construction isn't as deep as for 'if-else' or 'for.' At least mine... I faced one interesing case and wanted to share it with you. Let's take a look at the code:
int state = ...
...
List states = new ArrayList<>();
switch (state) {
case 0:
Integer newState = orderState + 1;
states.add(newState);
break;
case 1:
newState = orderState + 2;
states.add(newState);
break;
case 2:
newState = orderState + 3;
states.add(newState);
break;
default:
newState = orderState + 4;
states.add(newState);
}
Do you think this code is correct? Or maybe it should look like this:
int state = ...
...
List states = new ArrayList<>();
switch (state) {
case 0:
Integer newState = orderState + 1;
states.add(newState);
break;
case 1:
Integer newState = orderState + 2;
states.add(newState);
break;
case 2:
Integer newState = orderState + 3;
states.add(newState);
break;
default:
Integer newState = orderState + 4;
states.add(newState);
}
Should newState
be declared as a new variable in every case
or not? My first intention was to answer that the first variant is correct. Seemed obvious that switch
is the same as if-else
, but with some more if
cases inside. So we would declare a new variable in every condition branch.
But it is not correct. You should declare variable once in a switch expression and use it after in all the case
blocks. It can be explained very simply: every case
ends with break
, which prevents processing all subsequent case
s, but break
is optional. If there is no break
operator, then all operators under the first case
will be executed, then all operators under the second case
and etc. So without break
, it is simple part of code with the same scope, where all operators will be executed in usual order.
By the way, one more hint: {
and }
indicate the border of scope. Switch have one pair of {}
, so there is one scope, but if-else
could have one pair of {}
per if
and else
. That is why it is possible to declare the same variable in if
part and in else
part.
Published at DZone with permission of Ivan Zerin, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments