Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't the scope of a switch statement in Java limited?

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?

like image 898
sdasdadas Avatar asked Mar 13 '13 22:03

sdasdadas


People also ask

What Cannot be used in a switch statement?

The switch statement doesn't accept arguments of type long, float, double,boolean or any object besides String.

How many cases can a switch statement have in Java?

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.

What is the advantage of switch case in Java?

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.

Does switch work with long Java?

The switch statement works with byte, short, int, long, enum types, String and some wrapper types like Byte, Short, Int, and Long.


1 Answers

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.

like image 106
zw324 Avatar answered Sep 28 '22 19:09

zw324