简体   繁体   中英

Order of operations for compound assignment operators in Java

I came across the following on a mock exam recently, and was a bit lost as to why the answer given is 25, 25 according to the order of operations, and what I might be missing from the specification that gives the details as to why.

public class Test {

    public static void main(String[] args) {
        int k = 1;
        int[] a = {1};
        k += (k = 4) * (k + 2);
        a[0] += (a[0] = 4) * (a[0] + 2);
        System.out.println(k + " , " + a[0]);
    }
}

Just looking at line 6 above I substitute the appropriate values, and get the following:

k = k + (k = 4) * (k + 2);

I evaluate the parenthesis first, which indicates k has first been assigned to the value of 4, and subsequently is added to the number 2, giving the total of 6. This is how I interpret that:

k = k + 4 * 6;

Now this is where it gets confusing. According to the order of operations I get the following, which would be correct given the previous expression:

k = k + 24;

In my thinking at this point k should be 4 because that was the new assignment, but the answer is actually 25, and not 28. Apparently compound operators have some order of precedence I'm not understanding, or my substitution principles are not correct.

In this answer, I will only consider the k case, it is the same for the array.

int k = 1;
k += (k = 4) * (k + 2);
// k += (k = 4) * (k + 2)
// 1 += (k = 4) * (k + 2)
// 1 +=    4    * (k + 2) with k = 4
// 1 +=    4    *   6     with k = 4
// k = 25

The tricks here:

  • k += captures the value of k before doing the calculation. += is called a compound assignment operator . Quoting the relevant part of the JLS:

    the value of the left-hand operand is saved and then the right-hand operand is evaluated.

  • k = 4 returns the assigned value, so 4.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM