Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference in the output in Java

Tags:

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

like image 554
Arindam Mukherjee Avatar asked May 27 '11 05:05

Arindam Mukherjee


Video Answer


3 Answers

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

like image 97
paxdiablo Avatar answered Oct 18 '22 00:10

paxdiablo


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.

like image 22
oezi Avatar answered Oct 18 '22 02:10

oezi


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

like image 21
Prasoon Saurav Avatar answered Oct 18 '22 00:10

Prasoon Saurav