1
0

Increment Operator in Java

The increment operator (++) is used to increase the value of the integer type variable by one. The operator can be used as a prefix (before the operand) and a suffix (after the operand). For example, ++result; and result++; will both end up in the result being incremented by one. The only difference is that the prefix version (++result) increases the value of the variable before use, whereas the postfix version (result++) increases the value of the variable after using the original value in the expression. If you are just performing a simple increment, 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.

Program to illustrate the prefix/postfix unary increment, operator

class PrePostDemo1
{
    public static void main(String[] args)
    {
        int i=3;
        i++;
        System.out.println(i); // "4"
        ++i;
        System.out.println(i); // "5"
        System.out.println(++i); // "6" i is incremented first then printed
        System.out.println(i++); // "6" i is printed first then incremented
        System.out.println(i); // "7"
    }
}

Leave a Reply