Search code examples
javaexpressionoperator-keywordoperator-precedence

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


Solution

  • 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)