KnowledgeBoat Logo

Operators

Increment and Decrement Operators

ICSE Computer Applications



Increment and decrement operators are unary operators, they operate on only one operand.

The increment operator ++ adds 1 to the value of its operand and the decrement operator -- subtracts 1 from the value of its operand. The statement

a = a + 1;

can be rewritten using increment operator like this:

a++;

Similarly, this statement:

a = a - 1;

can be rewritten using decrement operator like this:

a--;

The increment and decrement operators have a special property unique to them. We can use them in postfix form where they follow the operand. We used this form in the example above. We can also use them in prefix form where they precede the operand.

Prefix and Postfix Increment and Decrement Operators

Let’s look at the below BlueJ program to understand the Prefix form of these operators:

public class PrefixIncrement
{
    public void demoPrefixIncr() {
        int a = 99;
        /*
         * With Prefix increment
         * first a is incremented
         * to 100. After that 
         * a is assigned to b
         */
        int b = ++a;
        System.out.println("a = " + a);
        System.out.println("b = " + b);
    }
}

Prefix form follows the CHANGE-THEN-USE rule. The prefix increment operator which we applied to a, will first increment the value of a by 1, making its value 100. After the increment, the incremented value of a gets assigned to b. Once the two statements finish executing, both a and b will have the value of 100.

This animation explains the sequence of steps in the prefix case:

Now let’s look at the postfix form:

public class PostfixIncrement
{
    public void demoPostfixIncr() {
        int a = 99;
        /*
         * With Postfix increment 
         * first a is assigned to
         * b. After that a is 
         * incremented
         */
        int b = a++;
        System.out.println("a = " + a);
        System.out.println("b = " + b);
    }
}

Postfix form follows the USE-THEN-CHANGE rule. In the postfix case, first the original value of a which is 99 gets assigned to b. After the assignment, the postfix increment operator increments the value of a to 100. Once the two statements finish executing, a will have the value of 100 and b will have the value of 99.

This animation explains the sequence of steps in the postfix case:

Prefix and Postfix Decrement operators work in a similar way to their Increment counterparts. Instead of increasing the value, they decrease the value by 1.

PrevNext