Postfix Prefix Increment Decrement Operator in Java: Figure 4.15 demonstrates the difference between the prefix increment and postfix increment versions of the ++ increment operator. The decrement operator (–) works similarly.
Line 9 initializes the variable c to 5, and line 10 outputs c’s initial value. Line 11 outputs the value of the expression c++. This expression postincrements the variable c, so c’s
original value (5) is output, then c’s value is incremented (to 6). Thus, line 11 outputs c’s
initial value (5) again. Line 12 outputs c’s new value (6) to prove that the variable’s value
was indeed incremented in line 11.
Line 17 resets c’s value to 5, and line 18 outputs c’s value. Line 19 outputs the value
of the expression ++c. This expression preincrements c, so its value is incremented; then
the new value (6) is output. Line 20 outputs c’s value again to show that the value of c is
still 6 after line 19 executes.
Postfix Prefix Increment Decrement Operator in Java
/*
* Filename: Increment.java
*
* Description: 4.15 - Pre and postfix increment operators.
*
* @Author: Bilal Tahir Khan Meo
* Website: https://codeblah.com
*
* =====================================================================================
*/
public class Increment{
public static void main(String[] args){
int c;
// postfix
c = 5;
System.out.println(c);
System.out.println(c++);
System.out.println(c);
System.out.println();
// prefix
c = 5;
System.out.println(c);
System.out.println(++c);
System.out.println(c);
}
}
Output of Program
c before postincrement: 5
postincrementing c: 5
c after postincrement: 6
c before preincrement: 5
preincrementing c: 6
c after preincrement: 6