# i++

vikas singh
Greenhorn
Posts: 8
int i=1;
i=i++;
System.out.println(i);
i=i++
Szystem.out.println(i);
i=i++
System.out.println(i)

In this above programe what the output we aspect 2,3,4 .But its not like this .The actual output wud be 1,1,1
I am not able to find why it is happening.Kindly somebody assist me in this problem.

Chandra Bhatt
Ranch Hand
Posts: 1710

int i=1;
i=i++;
System.out.println(i);
i=i++
Szystem.out.println(i);
i=i++
System.out.println(i)

i=i++;

'i' has a starting value of 1. The expression 'i++' evaluates to the pre-increment (original) value of 'i', or 1, this is because it is post increment happening there. The result of this expression (1) is remembered. The value of 'i' is then incremented ('i' is now 2). The '=' assignment operator has the least precedence, so it happens last: the result of the right-hand expression (what we remembered earlier, namely 1) is assigned back to 'i'. Therefore, the result of the whole statement is that 'i' has a value of 1.

You can try this:

Thanks and Regards,
cmbhatt

Arno Diederik
Greenhorn
Posts: 3
I'll give you a clou, let's do it the other way round:

int i=1;
i=++i;
System.out.println(i);
i=++i;
System.out.println(i);
i=++i;
System.out.println(i);

Hey the output is 2,3,4...

Below a quote from the java tutorial (http://java.sun.com/docs/books/tutorial/java/nutsandbolts/op1.html):

The increment/decrement operators can be applied before (prefix) or after (postfix) the operand. The code result++; and ++result; will both end in result being incremented by one. The only difference is that the prefix version (++result) evaluates to the incremented value, whereas the postfix version (result++) evaluates to the original value. If you are just performing a simple increment/decrement, it doesn't really matter which version you choose. But if you use this operator in part of a larger expression, the one that you choose may make a significant difference.

The following program, PrePostDemo, illustrates the prefix/postfix unary increment operator:

class PrePostDemo {
public static void main(String[] args){
int i = 3;
i++;
System.out.println(i);// "4"
++i;
System.out.println(i);// "5"
System.out.println(++i);// "6"
System.out.println(i++);// "6"
System.out.println(i);// "7"
}
}