Every variables have a scope. A scope is nested inside a bracket {}. when you go out of this scope, this context is gone, so you can defined other variables with same name. Otherwise, you cannot.
I will give you two examples:
// define new scope named "methodA"
public void methodA() {
int a = 3;
// define new scope named "loop"
for (int i = 0; i < 10; i++) {
int a = 6; // ERROR
}
}
In above case, you will meet error. because "loop" scope is inside "methodA" scope, so first definition of a still exist when you go to "loop" scope.
Second case:
// define new scope named "methodA"
public void methodA() {
// define new scope inside methodA scope
{
int a = 3;
}
// define new scope named "loop"
for (int i = 0; i < 10; i++) {
int a = 6; // NO ERROR
}
}
above code will compiled successfully, because first definition of a in different scope of second definition of a, and those scopes don't nested.
new.