Write in front: a few days ago finished the JVM memory structure, think oneself is understood, in the mind is not divided thread share and thread private, and then how how how how how.

Until I came across this problem. To be honest, I used to do this kind of arithmetic problem by myself. It was all in my head, and then I picked up the pen and wrote down an answer that I didn’t know was correct or not. But after today, I’m finally sure of the answer.

1, the title

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); }}Copy the code

Can you say your answer positively and accurately?

2, analysis,

We need to have the JVM memory structure in mind when we do this. One of these methods corresponds to a stack frame

For this problem we only need to use the local variable table and operand stack inside the stack frame

2.1. Step 1

int i = 1
Copy the code

It’s just a simple assignment

2.2. Step 2

i = i++
Copy the code

Result: I is still equal to 1

2.3. Step 3

int j = i++
Copy the code

Result: I becomes 2 in the local variable table, the value of I in the operand stack is 1, and the value of I is returned to j, i.e. after this statement, I = 2, j = 1

2.4. Step 4

int k = i + ++i * i++
Copy the code

Results: I = 4, K = 11 in the local variable scale

2.5, the results

If I = ++ I, I = ++ I, I = ++ I, I = ++ I Our variable I increments in the local variable table, then pushes I onto the stack, and then returns the stack to our variable I.

public class test02 { public static void main(String[] args) { int i = 1; i = ++i; System.out.println(i); // result: I = 2}}Copy the code

I = I ++ and I = ++ I