-2

I have following java code:

public class myClass {

    public static void main(String[] args) {

        System.out.println("Hello World!");

        int x = 20;
        int y = 10;

        double z = x++ - y * 7 / --y + x * 10;
        System.out.println(z);
    }
}

I got 223.0 output. But I would like to know the step by step process. Someone please explain it according to operator precedence.

Mihai Chelaru
  • 7,614
  • 14
  • 45
  • 51
Shanojan.A
  • 25
  • 5

1 Answers1

3

I decided to write up an answer because there's a gotcha in there that is unrelated to operator precedence (see step 3).

Step 0: The input expression—

   x++ - y * 7 / --y + x * 10;

Step 1: In terms of operator precedence, increment/decrement have a higher precedence than multiplication/division, and multiplication/division have a higher precedence than addition/subtraction, so add some parentheses to clarify that—

   (x++) - (y * 7 / (--y)) + (x * 10);

Step 2: The next thing to do is to replace the variables with values, taking into account how the pre/post-increment/decrement operators work—

   20 - (10 * 7 / 9) + (21 * 10)
//  ^             ^      ^
//  |           Pre-1    |
//  |                    |
//  + -----------------Post+1

Step 3: The only thing not related to operator precedence: performing an operation on integer operands yields an integer result, even if the result of the expression is assigned to a floating point type. Therefore, 10 * 7 / 9 yields 7

   20 - (7) + (210)

Step 4: Expressions are evaluated from left to right—

   20 - 7 + 210
   13 + 210
   223

Step 5: The integer result is assigned to a double

   223.0
Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156