Have you done this Java interview question correctly?

public class qusetion {
	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);
	}
}

I would like to ask, what are the results of i, j and k?

Think about it, the answer is:

i:4
j:1
k:11

Why, below, we will gradually analyze this process:

The first sentence is very simple: set the constant i = 1;

Second sentence: i = i ++;

                                                         

This process requires us to understand. Starting from "=", the assignment number is the slowest :

  • The first step is to put the value of i on the stack, then i-> 1
  • The second step: the value of i is incremented by 1, i-> 2
  • The third step: assign the value 1 in the stack to i, i-> 1

Third sentence: j = i ++; same as the second sentence

                                                    

  • The first step is to put the value of i on the stack, then i-> 1
  • The second step: the value of i is incremented by 1, i-> 2
  • The third step: assign the value 1 in the stack to [j], j-> 1
  • At this point it can be determined that the final j result is 1

Fourth sentence: k = i + ++ i * i ++;

                                    

  • The first step is to put the value of i on the stack, then i-> 2
  • The second step: ++ i: After the value of i is accumulated by 1, put it on the stack, i-> 3
  • The third step: i ++: The value of i is put on the stack, and i is incremented by 1, i-> 4. At this time, the operation of i ends, and finally i is determined to be 4
  • The three numbers in the stack are calculated, and the result is 3 * 3 + 2 = 11, assigned to k, and finally k is determined to be 1

 

Problem solving (spreading flowers)

Published 20 original articles · won 15 · views 216

Guess you like

Origin blog.csdn.net/qq_37414463/article/details/105443896