This question already has an answer here:
I know in c++ variables have block scope, for example, the following code works in C++
void foo(){
int a = 0;
for(int i = 0; i < 10; ++i){
int a = 1; //re-define a here.
}
}
but this snippet doesnt work in java, it reports "duplicate local variable a", does it mean java variables dont have BLOCK scope?
The previous answers already stated the reason, but I just want to show that this is still allowed:
In this case the
a
inside the loop doesn't hide the outera
, so it's valid.Also IMHO it should be this way in C++ too, it's less confusing and prevents accidental declaration of variable with same name.
It does, but it's nested, so the "a" you defined in foo() is available in all blocks within foo.
Here is an example of what you're looking for:
java variables do have a block scope but if you notice int a is already defined in scope
all subscopes are in scope of the uppermost curly braces. Hence you get a duplicate variable error.
They have block scope. That means that you can't use them outside of the block. However Java disallows hiding a name in the outer block by a name in the inner one.
Section §14.4.2
says: