I am reading about JVM architecture. Today I read about the concept of the Operand Stack. According to an article:
The operand stack is used during the execution of byte code instructions in a similar way that general-purpose registers are used in a native CPU.
I can't understand: What exactly is an Operand Stack, and how does it work in jvm?
The operand stack is used during the execution of byte code instructions in a similar way that general-purpose registers are used in a native CPU.
Java Virtual Machine, or JVM, loads, verifies and executes Java bytecode. It is known as the interpreter or the core of Java programming language because it executes Java programming.
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 int
s 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:
27
10
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With