Reputation: 139
I have found the following java code:
test:
for (int i = 0; i <= max; i++) {
int n = substring.length();
int j = i;
int k = 0;
while (n-- != 0) {
if (searchMe.charAt(j++) != substring.charAt(k++)) {
continue test;
}
}
foundIt = true;
break test;
}
System.out.println(foundIt ? "Found it" : "Didn't find it");
}
Inside the loop, the above code is creating 'n', 'j' and 'k' several times. How the program distinguishes between these variables of the same name?
I mean where they are stored in the memory to distinguish them?
Upvotes: 0
Views: 647
Reputation: 7290
With a bit of simplification:
Inside a { ... }
block, int k = 0;
creates a variable, and that variable exists up to the moment where you reach the end of the block, and there the variable gets destroyed. So, at any time during the program run, there's at most one n
, j
, or k
in existence.
A bit closer to reality:
The compiler scans the whole method, finds the list of variables that might exist in parallel (i
, n
, j
, k
, and foundIt
), and allocates enough places on the stack for these variables (5 places in your example). These stack places exist from the moment you enter your method until you return from it, but they are not used all the time, e.g. the k
place only contains useful values from the time you execute int k = 0;
to the end of the current loop iteration.
Upvotes: 1
Reputation: 140494
Java's local variables have a protection known as definite assignment this means that you can't read a value from them before you've assigned it a value.
They are also defined within a scope: you can only access the variable within a certain chunk of the program.
With the two of these things together, you don't need a separate variable for each iteration of the loop: you are guaranteed to assign a local variable a value before using it, so you are guaranteed to overwrite any value which was stored in it before, if any.
Variables are really just a helpful concept in the source code. Once compiled, the byte code doesn't have variable names: the compiler has simply determined that it can temporarily use a particular part of memory to store a value for a limited time. It will reuse this memory many times, but in ways that it guarantees do not overlap between usages.
Upvotes: 0