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

Answer:

int counter=0;

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

Increment after Use

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 the value it holds has been used. It is vital to understand the details of this:

This is confusing. It is best to use the ++ operator only with variables that are not part of a larger expression, as in the answer to the previous question.

The Java AP Examination does not expect you to use this operator in expressions or in assignment statements. However, it does use the operator to increment isolated integer variables in a counting loop. It does not use the operator with 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?


go to previous page   go to home page   go to next page