Why, in Java, is a variable's scope confined to a switch block as opposed to a case block. For example,
// Scope limited to a switch block
switch (number) {
case 1:
String result = "...";
break;
case 2:
result = "...";
break;
In the above example, result needs only to be declared once. If you declare it twice then you receive a Duplicate local variable
message.
My question is: how does the program know you've declared result
if number = 2
?
(It won't fall into case 1
and won't declare the variable... or will it?)
EDIT:
I might be confusing everyone. I understand how I can limit the scope of a variable but my question is: how does Java know that result has been declared if it doesn't fall into the case?
The switch statement doesn't accept arguments of type long, float, double,boolean or any object besides String.
Some Important points about Switch Statements in Java There is no limit for the number of cases in a switch statement. There can be one or 'N' number of cases in a switch statement.
The main reasons for using a switch include improving clarity, by reducing otherwise repetitive coding, and (if the heuristics permit) also offering the potential for faster execution through easier compiler optimization in many cases.
The switch statement works with byte, short, int, long, enum types, String and some wrapper types like Byte, Short, Int, and Long.
EDIT: Java uses lexical scoping (also called static scoping), so the scope of the variables are determined during compile time, and have nothing to do with the actual evaluation.
Java is block scoped, so it's scope will respect the {}
in the example above.
See JLS 6.3:
The scope of a local variable declaration in a block (§14.4) is the rest of the block in which the declaration appears, starting with its own initializer and including any further declarators to the right in the local variable declaration statement.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With