1
0

Decrement Operator in Java

Like the increment operator, the decrement operator (–) is used to decrease the value of the integer type variable by one. The operator can be used as a prefix and suffix. For example –result; and result–; will both decrease value of the result by one. The only difference is that the prefix version (–result) decreases the value of the variable before use, whereas the postfix version (result–) decreases the value of the variable after using the original value in the expression. If you are using this statement as an independent statement then it does not matter which version you choose. But if you use this operator as part of a larger expression, then the one you choose may make a significant difference.

Write a program to illustrate the prefix/postfix unary decrement, operator

class PrePostDemo2
{
    public static void main(String[] args)
    {
        int i=9;
        i--;
        System.out.println(i); // "8"
        --i;
        System.out.println(i); // "7"
        System.out.println(--i); // "6" i is decremented first then printed
        System.out.println(i--); // "6" i is printed first then decremented
        System.out.println(i); // "5"
    }
}

Leave a Reply