简体   繁体   中英

Explain Java Unary operator

Do check this code:

int result = 0;
result = result++;
System.out.println("Result 1 = " + result);
result++;
System.out.println("Result 2 = " + result);

The output i was expecting was :

Result 1 = 1
Result 2 = 2

But i got the output:

Result 1 = 0
Result 2 = 1

The problem lies at Line2. Can some one explain on Unary operator.??

In the statement i = i++ :

This is guarenteed behaviour. The value of i is read for the purposes of evaluating the righthand side of the assignment. i is then incremented. statement end results in the evaluation result being assigned to i .

There are two assignments in i = i++; and the last one to be executed will determine the result. The last to be executed will always be the statement level assignment and not the incrementer/decrementer.

Terrible way to write code, but there you have it a deterministic result at least.

http://forums.sun.com/thread.jspa?threadID=318496

当您执行x ++时,结果是增量之前的值

Replace this line:

result = result++;

with:

result++;

In the first line you're assigning zero to result. Why? Because the post-increment operator first will assign result's zero.

If you had written:

result = ++result;

You would first increment and then assign, also getting the result you wanted.

You need to be conscious of where you place the unary operator. Placing ++ after a variable causes java to evaluate the expression using the variable then increment the variable, while placing the ++ before the variable causes java to increment the variable and then evaluate the expression.

This is the expected behaviour. What is actually happening makes more sense if you look at what happens at the bytecode level when the line in question executes:

result = result++;

registerA = result (registerA == 0)
result += 1 (result == 1) -- These first two lines are the result++ part
result = registerA (result == 0)

The variable "result" is being assigned twice in this statement, once with an increment, and then again with the value prior to the increment which basically makes it a noop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM