Postfix Increment Operator

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   hear noise   go to next page

Answer:

int counter=0;

while ( counter < 10 )
{
  System.out.println("counter is now " + counter );
  counter++ ;
}

Postfix Increment Operator

The postfix increment operator ++ adds one to a variable. Usually the variable is an integer type (byte, short, int, or long) but it can be a floating point type (float or double). No character is allowed between the two plus signs. The postfix operator must follow the variable. Usually it is put immediately adjacent to the variable, as above, although this is not necessary.

The postfix increment operator can be used as part of an arithmetic expression, as in the following:

int sum = 0;
int counter = 10;

sum = counter++ ;

System.out.println("sum: " + sum + " counter: " + counter );

This program fragment will print:

sum: 10  counter: 11 

The statement sum = counter++; increments the variable counter after it has been used. It is vital to understand the details of this:

  • The assignment statement is executed in two steps:
    1. Evaluate the expression on the right of the =
      • the value is 10 (because counter has not been incremented yet.)
    2. Assign the value to the variable on the left of the =
      • sum gets 10.
  • Now the ++ operator works: counter is incremented to 11.
  • The next statement writes out: sum: 10 counter: 11

This is confusing. I advise that you use the ++ operator only to increment isolated variables, as in the answer to the previous question. The Java AP Examination does not test students on using this operator in expressions or in assignment statements. However, it does use the operator to increment isolated variables. Also, it does not use the operator on floats or doubles.

QUESTION 3:

Inspect the following code:

int x = 99;
int y = 10;

y = x++ ;

System.out.println("x: " + x + "  y: " + y );

What does the above program print?