开发者

unable to make out this assignment in java

开发者 https://www.devze.com 2022-12-21 18:12 出处:网络
can anybody expla开发者_StackOverflowin this why its happening int i=0; i=i++; i=i++; i=i++; System.out.println(i);

can anybody expla开发者_StackOverflowin this why its happening

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

it prints zero.


i++ is a postincrement (JLS 15.14.2). It increments i, but the result of the expression is the value of i before the increment. Assigning this value back to i in effect keeps the value of i unchanged.

Break it down like this:

int i = 0;
int j = i++;

It's easy to see why j == 0 in this case. Now, instead of j, we substitute the left hand side with i. The right hand side value is still 0, and that's why you get i == 0 in your snippet.


You meant to do this:

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

i++ actually does an assignment so if you add an = you just confuse things. These other fine responders can give you the nitty gritty, some details of it escape me. :)


First thing is you should not write this kind of code....

But if we consider for the questions sake then this simple: It has to do with the way the postfix operator "returns" the value. A postfix has precedence over the assignment operator, but the postfix operator after incrementing the value of i returns previous value of i. So i get again assigned to its previous value.

And once again don't use this construct in your code as the next programmer who sees this will come after you (with something big in his hands) :)


Let I=++, an increase, and A=i, an assignment. They are non-commutative: IA != AI.

Summary

IA = "first increase then assignment"

AI="first assignment then increase"

Counter-Example

$ javac Increment.java 
$ java Increment 
3
$ cat Increment.java 
import java.util.*;
import java.io.*;

public class Increment {
    public static void main(String[] args) {
        int i=0;
        i=++i;
        i=++i;
        i=++i;
        System.out.println(i);
    }
}

Related

  • Initialization, assignment and declaration
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号