Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a Java method have more than 255 local variables?

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?

like image 224
corazza Avatar asked Dec 24 '12 22:12

corazza


1 Answers

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!

like image 111
templatetypedef Avatar answered Sep 21 '22 15:09

templatetypedef