Understanding Java Increment Operators and JVM Stack Frame Behavior
This article explains a Java interview puzzle by analyzing how the JVM stack frame handles variable assignments and increment operators, step‑by‑step showing the effects of i = i++, i = ++i, and a complex expression i + ++i * i++ on variable values.
The post introduces a Java interview question series and encourages readers to follow the related WeChat public account for more Java interview problems.
It then presents a Java program ( test01) that manipulates variables i, j, and k using post‑ and pre‑increment operators, and prints their final values.
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);
}
}The analysis explains each step using the JVM stack frame concepts of the local variable table and operand stack.
1. First step
Assign int i = 1 – a simple initialization.
2. Second step
Execute i = i++. Because the post‑increment returns the original value, i remains 1.
3. Third step
Execute int j = i++. After this statement, the local variable table holds i = 2 while the operand stack returned the previous value 1, so j = 1.
4. Fourth step
Execute int k = i + ++i * i++. The evaluation order leads to i = 4 in the local variable table and k = 11.
The resulting values are shown in the accompanying image.
5. i = ++i
A second example ( test02) demonstrates the pre‑increment case, where i = ++i yields i = 2.
public class test02 {
public static void main(String[] args) {
int i = 1;
i = ++i;
System.out.println(i); // result: i = 2
}
}The article concludes that the reasoning and calculations are specific to the Java language and its JVM execution model.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Selected Java Interview Questions
A professional Java tech channel sharing common knowledge to help developers fill gaps. Follow us!
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.
