Increment And Decrement Operators can be used both
postfix (
x++
) and
prefix (
++x
). In the postfix form it is used and then incremented, where as in prefix form it is incremented and then used.
int x = 42;
int y = ++x; // same as x = x + 1; followed by int y = x;
System.out.println("x = " + x + " y = " + y);
The above code prints
x = 43 y = 43
where as the below code prints
x = 43 y = 42
int x = 42;
int y = x++; // same as int y = x; followed by x = x + 1;
System.out.println("x = " + x + " y = " + y);
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);
}
}
OUTPUTa = 6 b = 3 c = 4 d = 5
DESCRIPTIONHere 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
.
2-min video about Increment and Decrement operators