Why is the scope of switch statements in Java unlimited?

Why in Java, the scope of variables is limited to switch blocks rather than case blocks For example,

// Scope limited to a switch block
switch (number) {
case 1:
    String result = "...";
    break;
case 2:
    result = "...";
    break;

In the above example, the result needs to be declared only once If you declare it twice, you will receive duplicate local variable message

My question is: if number = 2, how does the program know that you have declared the result? (it will not belong to case 1, nor will it declare variables... Or will it?)

Edit:

I may confuse everyone I understand how to limit the scope of variables, but my question is: if this is not the case, how does Java know that the result has been declared?

Solution

Edit: Java uses lexical scope (also known as static scope), so the range of variables is determined during compilation, independent of the actual evaluation

Java is a block scope, so its scope will respect {} in the above example

See JLS 6.3:

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>