go to previous page   go to home page   hear noise   go to next page


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:

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.


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?