简体   繁体   中英

java expression calculation and operator precedence

i have problem to step by step java expression calculation

System.out.println(++x + x++ * y-- - --y);

I know this precedence: 1. postfix unary 2. prefix unary 3. multiplicative 4. additive

but when i calculate with this precedence the result is below: // 12 + 11 * 19 - 18 can some one help me

You can understand it from the example given below:

public class Main {
    public static void main(String[] args) {
        int x = 5, y = 10;
        System.out.println(++x + x++ * y-- - --y);// 6 + 6 * 10 - 8 = 58
    }
}

Steps in this calculation:

  1. ++x = 6
  2. 6 + x++ * y-- = 6 + 6 * 10 = 6 + 60 = 66 (after this y will become 9 because of y-- and x will become 7 because of x++ but this increased value of x has never been used in subsequent calculation)
  3. 66 - 8 = 58 (before y gets subtracted from 66 , it will become 8 because of --y )

Postfix unary is applied after the variable evaluation, opposite to prefix, which is applied before evaluation, your expression can be rewrited:

int x_prefix = x + 1; // ++x
int y_prefix = y - 1; // --y

System.out.println(x_prefix + x * y - y_prefix);

int x = x + 1; // x++
int y = y - 1; // y--

You write operators precedence, it's right but every operator has own behavior, in case of postfix increment, of course has to be evaluate before others, but its behavior is return the current variable and after increment its value.

NOTE: I just rewrited your expression as is, if you use in the same expression the variable postfix incremented, the next access see the variable incremented:

int x = 1;

System.out.println(x++ + x++); // 1 + 2
System.out.println(x) // 3

For completeness:

int x = 1;

System.out.println(++x + ++x); // 2 + 3
System.out.println(x) // 3

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