Each variable has a scope. The area is nested inside the bracket {} . when you leave this area, this context is gone, so you can define other variables with the 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 the above case, you will encounter an error. because the loop area is inside the methodA area, so the first definition still exists when you go into the loop area.
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 } }
the above code will be compiled successfully, because the first definition of a in another area of โโthe second definition of a and those areas are not nested.
source share