I have one program in java..i am confused about the output.
public static void main(String args[])
{
        int n=0;
        for(int m=0; m<5;m++)
        {
            n=n++;
            System.out.println(n);
        }
}
here output is 0 0 0 0 0
But if i write,
public static void main(String args[])
{
        int n=0;
        for(int m=0; m<5;m++)
        {
            n++;
            System.out.println(n);
        }
}
then output is 1 2 3 4 5
Why it is coming like this???
Because, in the first snippet, n++ resolves to n before the increment. So, when you do:
n = n++;
it saves n, then increments it, then writes the saved value back to n.
In the second snippet, that assignment isn't happening so the increment "sticks".
Think of the operations as follows, with the order of actions being from the innermost [ ] characters to the outermost:
[n = [[n]++]]                    [[n]++]
- current n (0) saved.           - current n (0) saved.
- n incremented to 1.            - n incremented to 1.
- saved n (0) written to n.      - saved n (0) thrown away.
If you want to increment n, you should just use n = n + 1; or n++;.
thats because you're using post-increment (n++) instead of pre-increment (++n). this line will do what you're expecting:
n = (++n);
PS: yes, the links explain this for c/c++, but the behaviour is the same in almost every programming-language.
EDIT: thanks to Prasoon Saurav and paxdiablo, i've learned something new today. the linked sites might be wrong for c and c++, but they still explain what happens in java.
n=n++;
The evaluation order is from left to right. 
After each iteration n gets assigned to 0 because n++ evaluates to n before the increment.  
So that's what you get as the output.
You should write n = n+1 to get the desired output..
P.S : On a sidenote n = n++ invokes Undefined Behaviour in C and C++. ;-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With