tags:

views:

333

answers:

5

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.??

+2  A: 

When you do x++, the result is the value before the incrementation

Uri
+5  A: 

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

Miles
+1  A: 

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.

omgzor
A: 

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

beggs
+1  A: 

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.

qdolan