Menu
Topics Index
...
`

Pre and Post Increment - Java Example Program


Pre and Post Increment
class PreAndPostIncrement
{
    public static void main(String arg[])
    {
        int a = 5;
        int b = 2;
        int c;
        int d;
        c = ++b; // LINE A
        d = a++; // LINE B
        c++; // LINE C
        System.out.println("a = " + a + " b = " + b + " c = " + c + " d = " + d);
    
    }
}
OUTPUT

a = 6 b = 3 c = 4 d = 5

DESCRIPTION

Here a and b are declared as integers and they are assigned to 5 and 2 respectively.
In LINE A, we have prefix increment operator i.e. ++ before the operand b i.e. ( ++b ). So the value of b is first incremented from 2 to 3 and then assigned to c. Hence c becomes 3.
In LINE B, where we have postfix increment operator i.e. ++ after the operand a i.e. ( a++ ), the value of a is first assigned to d, so d becomes 5. Later a is incremented from 5 to 6.
In LINE C, c is incremented, so it goes from 3 to 4. Here there is no difference whether we use postfix ( c++ ) or prefix ( ++c ) increment since we are not assigning it or using it as part of some other expression.

THINGS TO TRY
  • Change LINE A to c = b++; and LINE B to d = ++a; and see what will be the output.
  • Use decrement operator -- instead of increment operator by changing LINE A to c = --b; and LINE B to d = --a; and validate the output. The decrement operator decreases the value of operand by 1. If it was 4, it will become 3.

© meritcampus 2019

All Rights Reserved.

Open In App