Java allows local variables (or parameters) to have the same name as instance variables. The local variable then hides the instance variable. However, the instance variable can still be reached by using the this reference.
public class Example {
int i; // Instance variable
public void exampleMethod() {
int i; // Local variable
i = 0; // Accesses the local variable
this.i = 10; // Access the instance variable
}
}
It is not uncommon to see something like the following...
public class Example {
int value;
public Example(int value) {
this.value = value; // Assigns the value of the local
// parameter to the instance variable
}
}
Java (unlike C++) does not allow variables in nested blocks to have the same name. For example...
int i = 0;
int x = 0;
while (x < 10) {
int i; // Will cause an error: i already exists
.
.
x++;
}
However, Java variables (like C++) only exist in the block in which they are declared. For example...
int x = 0;
while (x < 10) {
int i = 5;
.
.
x++;
}
x = i; // Will cause an error: i does not exist here
The same is true of for loops. Variables declared in the for statement cannot have the same name as already existing variables and they only exist for the lifetime of the loop.
int i = 5;
for (int i = 0; i < 10; i++) { // Will cause an error: i already exists
.
.
}
for (int i = 0; i < 10; i++) {
.
.
}
i = 5; // Will cause an error: i does not exist here
And since the for index is considered to only exist inside the loop, the following is allowed in Java...
for (int i = 0; i < 10; i++) {
.
.
}
for (int i = 0; i < 10; i++) { // OK: the previous i is gone
.
.
}
The if statement also works the same way...
int i = 0;
if (i < 10) {
int i; // Will cause an error: i already exists
.
.
}
int x = 0;
if (x < 10) {
int i = 0;
.
.
}
i = 10; // Will cause an error: i does not exist here