Question

Is there a bijective mapping between the local variables in the source code of a Java method and the byte code?

E.g.

source code:

int x = ...
A a = ....
if (...) {
    B b = ....
}

I can assume in the byte code there will be space for 3 local vars, where the first relates to x, the second to a and the third to b?

Will the ordering of the local vars in the bytecode relate to the ordering they are first used in the Java source?

EDIT: I'm aware that for longs and doubles Java uses two local variables and that there are local variables reserved for method params

Was it helpful?

Solution

Is there a bijective mapping between the local variables in the source code of a Java method and the byte code?

There isn't in general because addresses used by variables out of scope are reused for other in-scope variables. For example:

for (int j = 0;;) {}
int k  = 0;

k can reuse the same location as j.

OTHER TIPS

No, because the compiler can optimize your code and therefore variables could be eliminated. Simply think of a piece of code like this:

int a = 1; // only used to initialize b
int b = a;

Then it would be unnecessary to keep space for a. Or, for your example

int x = 42; // only used to initialize a
A a = new A(x);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top