Understanding Java Increment Operators and JVM Stack Frame Behavior
This article explains how Java's post‑ and pre‑increment operators affect variable values by tracing each statement through the JVM's stack frame, local variable table, and operand stack, and demonstrates the resulting values of i, j, and k with detailed diagrams and code examples.
The author analyzes a Java program that uses various increment operations to illustrate how the JVM manages local variables and the operand stack during execution.
package pers.mobian.questions01;
public class test01 {
public static void main(String[] args) {
int i = 1;
i = i++;
int j = i++;
int k = i + ++i * i++;
System.out.println("i="+i);
System.out.println("j="+j);
System.out.println("k="+k);
}
}Step 1: int i = 1 – a simple assignment places the value 1 in the local variable table.
Step 2: i = i++ – the post‑increment returns the original value, so i remains 1 after this statement.
Step 3: int j = i++ – the current value of i (1) is stored in j , then i is incremented to 2.
Step 4: int k = i + ++i * i++ – the expression is evaluated using the current stack state, resulting in i = 4 and k = 11 .
The final values after the first program are i = 4 , j = 1 , and k = 11 , as shown in the summary diagram.
public class test02 {
public static void main(String[] args) {
int i = 1;
i = ++i;
System.out.println(i); // result: i = 2
}
}For the second example, the pre‑increment i = ++i first increments i to 2, then stores the new value back, yielding i = 2 .
Note: All analysis and results are specific to the Java language and its JVM execution model.
Java Captain
Focused on Java technologies: SSM, the Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading; occasionally covers DevOps tools like Jenkins, Nexus, Docker, ELK; shares practical tech insights and is dedicated to full‑stack Java development.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.