Java – the job gives an unexpected answer

Today, I encountered the following problems, and I can't seem to find a solution:

int i,j,k;

i = j = k = 3;

i = k++;

So for me, the variable 'I' must now have a value of 4, because it seems logical for us to assign the increment of 'k' to it In the multiple-choice test, the correct value after the third line replaces:

k = 4

and

i != 4

Since we assign the increment of K to I, the given solution is exactly the opposite of what I expected Thank you in advance!

Solution

First, as JB nizet said, don't do this Occasionally I use suffix increment in another expression. For things like array [index] = value, but for clarity, I often divide it into two statements

I won't answer this question, but all the answers (when published) make the same mistake: it's not a matter of time; This is the problem of the value of expression K

The allocation of I occurs after the increment of K, but the value of expression K is the original value of K, not the incremental value

So this Code:

i = k++;

amount to:

int tmp = k;
k++;
i = tmp;

From section 15.14 2 of the JLS (key points):

This difference is very important. You can easily see that if you do not use the postfix expression as an assignment, you call a method:

public class Test {

    private static int k = 0;

    public static void main(String[] args) throws Exception {
        foo(k++);
    }

    private static void foo(int x) {
        System.out.println("Value of parameter: " + x);
        System.out.println("Value of k: " + k);
    }
}

The result is:

Value of parameter: 0
Value of k: 1

It can be seen that when we call it a method, K has increased, but the value passed to the method is still the original value

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>