Java output difference

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 the 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 the output will be 1 2 3 4 5

Why is this happening like this?

+5
source share
4 answers

Because the first fragment n++resolves to nbefore incrementing. So when you do this:

n = n++;

it saves n, then increments it, and then writes the saved value back to n.

In the second fragment, this assignment does not occur, therefore the increment "sticks".

Think of the following operations: the procedure 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.

n, n = n + 1; n++;.

+13

thats, post-increment (n ++) pre-increment (++ n). , :

n = (++n);

PS: , c/++, .

EDIT: Prasoon Saurav paxdiablo, - . c ++, , java.

+5

n=n++;

- . n 0, n++ n .

, .

n = n+1, .

PS: On the sidenote side n = n++, Undefined Behavior is invoked in C and C ++ .; -)

+2
source

n ++ means "return the current value and then increase". So what you do is returning 0, incrementing to 1, and then assigning the previous value (0) back to n.

The end result - n remains 0.

0
source

All Articles