Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unable to make out this assignment in java

Tags:

java

can anybody explain this why its happening

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

it prints zero.

like image 865
Ankit Sachan Avatar asked Mar 04 '10 05:03

Ankit Sachan


People also ask

What does %D stand for in Java?

The %d specifies that the single variable is a decimal integer. The %n is a platform-independent newline character. The output is: The value of i is: 461012. The printf and format methods are overloaded.

Can I assign this in Java?

According to the definition "this" is a keyword which acts as a reference to the current object (the object from whose constructor/method you are using it), its value id is fixed. Therefore, you cannot assign a new reference value to it. Moreover, it is just a keyword, not a variable.

Can you do multiple assignment in Java?

Java permits the use of multiple assignments in one statement. In such statements, the assignment operators are applied from right to left, rather than from left to right.

Does ++ change the value of the variable Java?

If we use the "++" operator as a prefix like ++varOne; , the value of varOne is incremented by one before the value of varOne is returned. If we use ++ operator as postfix like varOne++; , the original value of varOne is returned before varOne is incremented by one.


2 Answers

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.

like image 138
polygenelubricants Avatar answered Sep 24 '22 00:09

polygenelubricants


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. :)

like image 44
easeout Avatar answered Sep 24 '22 00:09

easeout