What is an operand stack?

It’s how the various individual bytecode operations get their input, and how they provide their output.

For instance, consider the iadd operation, which adds two ints together. To use it, you push two values on the stack and then use it:

iload_0     # Push the value from local variable 0 onto the stack
iload_1     # Push the value from local variable 1 onto the stack
iadd        # Pops those off the stack, adds them, and pushes the result

Now the top value on the stack is the sum of those two local variables. The next operation might take that top stack value and store it somewhere, or we might push another value on the stack to do something else.

Suppose you want to add three values together. The stack makes that easy:

iload_0     # Push the value from local variable 0 onto the stack
iload_1     # Push the value from local variable 1 onto the stack
iadd        # Pops those off the stack, adds them, and pushes the result
iload_2     # Push the value from local variable 2 onto the stack
iadd        # Pops those off the stack, adds them, and pushes the result

Now the top value on the stack is the result of adding together those three local variables.

Let’s look at that second example in more detail:

We’ll assume:

  • The stack is empty to start with (which is almost never actually true, but we don’t care what’s on it before we start)
  • Local variable 0 contains 27
  • Local variable 1 contains 10
  • Local variable 2 contains 5

So initially:

+−−−−−−−+
| stack |
+−−−−−−−+
+−−−−−−−+

Then we do

iload_0     # Push the value from local variable 0 onto the stack

Now we have

+−−−−−−−+
| stack |
+−−−−−−−+
|   27  |
+−−−−−−−+

Next

iload_1     # Push the value from local variable 1 onto the stack
+−−−−−−−+
| stack |
+−−−−−−−+
|   10  |
|   27  |
+−−−−−−−+

Now we do the addition:

iadd        # Pops those off the stack, adds them, and pushes the result

It “pops” the 10 and 27 off the stack, adds them together, and pushes the result (37). Now we have:

+−−−−−−−+
| stack |
+−−−−−−−+
|   37  |
+−−−−−−−+

Time for our third int:

iload_2     # Push the value from local variable 2 onto the stack
+−−−−−−−+
| stack |
+−−−−−−−+
|    5  |
|   37  |
+−−−−−−−+

We do our second iadd:

iadd        # Pops those off the stack, adds them, and pushes the result

That gives us:

+−−−−−−−+
| stack |
+−−−−−−−+
|   42  |
+−−−−−−−+

(Which is, of course, the Answer to the Ultimate Question of Life the Universe and Everything.)

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)