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++;counter after
it has been used.
It is vital to understand the details of this:
- The assignment statement is executed in two steps:
- Evaluate the expression on the right of the
=- the value is 10 (because
counterhas not been incremented yet.)
- the value is 10 (because
- Assign the value to the variable on the left of the
=- sum gets 10.
- Evaluate the expression on the right of the
- Now the
++operator works:counteris 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?