Question

The iload Java opcode is used to push a value from the local variable array (LVA) onto the operand stack.

This opcode takes a single byte as a parameter (en.wikipedia.org/wiki/Java_bytecode_instruction_listings), which serves as an index for the LVA.

If one element of the LVA is always the reference to the object (I guess this isn't the case for static methods, but lets ignore those for now), and if exactly one byte is used as an index (256 possible values), then how can a method have access to more than 255 different local variables?

Was it helpful?

Solution

Yes, it is possible for Java methods to have more than 255 local variables. The wide opcode instruction can be used to modify an iload or aload instruction to use a 16-bit index instead of an 8-bit index, meaning that you can have up to 65536 different local variables in a function, as long as the wide opcode ends up getting used.

That said, note that Java local variables do not necessarily correspond one-to-one with JVM local variables. It's possible that the Java compiler could look at your code, notice that space for locals can be reused in some contexts, then map multiple Java locals to the same JVM local variables.

Hope this helps!

OTHER TIPS

I tried it for you by writing a program with 300 local vars. This snippet:

System.out.println(a255);
System.out.println(a256);

compiles into this:

3575: getstatic     #16                 // Field java/lang/System.out:Ljava/io/PrintStream;
3578: iload         255
3580: invokevirtual #53                 // Method java/io/PrintStream.println:(I)V
3583: getstatic     #16                 // Field java/lang/System.out:Ljava/io/PrintStream;
3586: iload_w       #256                // Utf8 a196
3590: invokevirtual #53                 // Method java/io/PrintStream.println:(I)V

Note: compiled with Eclipse and javac, with exact same results.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top