java - Unary Operations fused with assignment -


doubtful result in following code:

public static void main (string[] args) {  int = 2; = i+=2 + i++; system.out.println(i); } 

was expecting 8 output, 'i+=2' should update i, not behaving so.

output: 6

i infer short-hand assignment operator returning 4 expected not updating same in variable i. explanation appreciated.

i++ postfix increment - increments i, returns old value of i. equivalent prefix operator, ++i, return "updated" value, that's not what's being used here.

i+=2 works differently however, it's equivalent i+2, since does return updated value.

however, think confusion arises you're looking @ this:

i = (i += 2) + i++; 

...which does give expected result. i+=2 gives 4, , updates i 4, i++ returns 4 (instead of 5 since it's post increment.) however, when take operator precedence equation, java "brackets" default:

i = += (2 + i++); 

just clear confusion, java evaluates way because += operator has least precedence in example, , therefore addition expression (+) calculated first.

this bracketed statement equivalent to:

i = (i = + (2 + i++)); 

which in turn simplifies to:

i = + (2 + i++); 

so given above statement, , evaluating left right, first take value of (2), , add value of 2+i++; latter giving 4 (because of postfix increment). our final result 2+4, 6.


Comments

Popular posts from this blog

php - Why I am getting the Error "Commands out of sync; you can't run this command now" -

linux - Does gcc have any options to add version info in ELF binary file? -

java - Are there any classes that implement javax.persistence.Parameter<T>? -