Skip to main content


1 reply [Last post]
Joined: 2010-05-31

couldn't understand this code
In the following program, explain why the value "6" is printed twice in a row:
class PrePostDemo {
public static void main(String[] args){
int i = 3;
System.out.println(i); // "4"
System.out.println(i); // "5"
System.out.println(++i); // "6"
System.out.println(i++); // "6"
System.out.println(i); // "7"

The code System.out.println(++i); evaluates to 6, because the prefix version of ++ evaluates to the incremented value. The next line, System.out.println(i++); evaluates to the current value (6), then increments by one. So "7" doesn't get printed until the next line.

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
Joined: 2010-08-16

The behavior of this operator depends on its position relativ to the operand.

When used before the operand, where it ihs known as the[b][i] pre-increment [/i][/b]operator, it increments the operand and evaluates to the incremented value of that operand. When used after the operand, where it is known as the[b][i] post-increment [/i][/b]operator, it increments its operand, but evaluates to the value of that operand before it was incremented.

For example, the following code sets both i and j to 2:

i = 1;
j = ++i;

But there lines set i to 2 and j to 1:

i = 1;
j = i++;

First Post :)

Message was edited by: elmu1