Could not determine this job in java

can someone explain this why this is happening

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

it prints zero.

+7
java
source share
4 answers

i++ is post-inconsistency ( 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 essentially keeps the value of i unchanged.

Divide it as follows:

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

It is easy to see why j == 0 in this case. Now, instead of j substitute the left side in i . The value of the right side is still 0 , and so you get i == 0 in your fragment.

+14
source share

You wanted to do this:

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

i++ really does the job, so if you add = , you are just confusing things. These other minor defendants can give you nitty gritty, some details about this are running away from me. :)

+4
source share

Firstly, you should not write such code ....

But if we look at the issues, then it's simple: this is due to how the postfix operator "returns" a value. The postfix takes precedence over the assignment operator, but the postfix operator after increasing the value i returns the previous value i. So I reassign its previous value.

And again, do not use this construct in your code, since the next programmer who sees that this will happen after you (with something big in his hands) :)

0
source share

Let I=++ , increase and A=i be the destination. They are not 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); } } 

Similar

  • Initialization, Purpose, and Declaration
0
source share

All Articles