Order of operations for compound assignment operators in Java

后端 未结 1 1336
名媛妹妹
名媛妹妹 2021-01-22 05:04

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 mi

相关标签:
1条回答
  • 2021-01-22 05:59

    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.
    0 讨论(0)
提交回复
热议问题