What is the scope of Java variables in the block?
•
Java
See English answers > why does Java not have block scoped variable declarations? 6
void foo(){ int a = 0; for(int i = 0; i < 10; ++i){ int a = 1; //re-define a here. }
}
However, this fragment does not work in Java. It reports "repeated local variable a". Does it mean that the Java variable has no block range?
Solution
Java variables do have a block scope, but if you notice that int is already defined in the scope
{ int a = 0; { { } } }
All child ranges are within the top curly bracket Therefore, you will receive duplicate variable errors
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
二维码