Wednesday 10 June 2015

Unary Operators Demo 2

public class PrePostDemo {
        /* In Java the unary operators ++ and -- can appear
         * before or after the variable. This will affect
         * how a program behaves.
         */
        public static void main(String[] args) {
                // ++ added before the variable.
                int result = 0;
                ++result;
                System.out.println(result);
                result = 0; // reset result to 0.
                System.out.println(++result);

                // ++ added after the variable.
                result = 0;
                result++;
                System.out.println(result);
                result = 0; // reset result;
                System.out.println(result++);

                /* Why wasn't result incremented by 1? The answer
                 * is, it was. As the next line of code will prove.
                 */

                System.out.println(result);

                /* So what's going on? The Oracle tutorial explains
                 * it like so "The only difference is that the prefix
                 * version (++result) evaluates to the incremented value,
                 * whereas the postfix version (result++) evaluates to
                 * the original value."
                 * 
                 * In practice, in this example, the prefix ++ increments
                 * result before the expression or line of code is completed.
                 * The postfix version increments result after the expression
                 * or line of code is completed. Which is why result is incremented
                 * when printed again with the additional println() call.
                 * 
                 * The -- decrement operator works in the same way.
                 */
        }
}

No comments:

Post a Comment

Translate