Search code examples
operator-precedence

java programming unary operator precedence


I want know how the operator precedence works on below code.

public class test {

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

}

i got 3 6 as out put......But I din't understand how it works. can anyone explain how it works.


Solution

  • a++ means that a is incremented after evaluation

    ++a means that a is incremented before evaluation

    a is incremented three times in total, so its value is 3 after the expression is computed.

    b= a++ + ++a * ++a; means that a is evaluated (0), then incremented, this (0) is added to the result of ++a * ++a, which means that the left part is 2 (because a, which is 1 from before, is incremented before evaluation, thus is evaluated as 2), and the right part is 3 (a was 2, and is incremented before evaluation, so it evaluated as 3). Thus the result of the expression is 2 * 3 = 6.

    To explain these incrementations a bit better:

    x = ++a; is like a = a + 1; x = a;

    x = a++; is like x = a; a = a + 1;