package expressions;

public class UnaryOps {
    public static void main(String[] args) {

        /*
         * Unary operators have only one operand. The two
         * mathematical unary operators in Java are:
         * ++ increment (add 1 to the value)
         * -- decrement (subtract 1 from the value)
         * 
         * Both operators can be "post-fix" or "pre-fix":
         * this means that the operand can go before or after
         * the operator. However, note that they do operate
         * differently.
         */

        System.out.println("first example");
        int x = 1;
        x++; // unary increment
        System.out.println(x);

        // what about this?
        System.out.println(x++);
        // do you get the output you expected?
        // System.out.println(x); // see what's in x

        // go to the x++ up above and move the x
        // after e.g. println(++x) - how does it change?

        // order of precedence chart:
        // https://www.cs.bilkent.edu.tr/~guvenir/courses/CS101/op_precedence.html
        // post-increment and pre-increment have different levels of precedence

        /*
         * Think of it this way:
         * ++x will increment first, then the new value of x is used
         * x++ the value of x is used first, then x is incremented
         */

        System.out.println("second example");
        int a = 1;
        System.out.println(a++); // prints a (1) then increments a to 2
        System.out.println(++a); // increments a (to 3) then prints a (3)

        // same thing happens in expressions with other operations:
        x = 1; // reset x to 1
        a = 2; // reset a to 2
        int result = x + a++; // x + a (1 + 2), then increment a to 3
        System.out.println(result + ", " + a);
        x = 1; // reset x to 1
        a = 2; // reset a to 2
        result = x + ++a; // increment a to 3, then add new a (3) to x (1)
        System.out.println(result + ", " + a);

        /*
         * Note that this also applies to the pre-decrement
         * and post-decrement:
         */
        x = 1; // reset x
        System.out.println(x--);
        System.out.println(--x);
    }
}
