简体   繁体   中英

Java - bijective mapping between local vars in source code vs byte code

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

Eg

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

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 .

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM