Arindam Mukherjee
Arindam Mukherjee

Reputation: 2285

Difference in the output in Java

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???

Upvotes: 5

Views: 254

Answers (4)

paxdiablo
paxdiablo

Reputation: 882616

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++;.

Upvotes: 13

oezi
oezi

Reputation: 51817

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.

Upvotes: 5

Mike Lanzetta
Mike Lanzetta

Reputation: 361

n++ means "return the current value, then increment". So what you're doing is returning 0, incrementing to 1, then assigning the previous value (0) back to n.

End result - n stays 0.

Upvotes: 0

Prasoon Saurav
Prasoon Saurav

Reputation: 92922

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++. ;-)

Upvotes: 2

Related Questions