operators - precedence of ~ and ++ in java -
consider code snippet
int j = 7; system.out.println(integer.tobinarystring(j)); j = ~j++; system.out.println(integer.tobinarystring(j)); prints
111 11111111111111111111111111111000 what expecting see
111 11111111111111111111111111111001 first thought might precedence of ~ , ++
if ~ evaluated before ++ answer
11111111111111111111111111111001 else if ++ evaluated before ~
11111111111111111111111111110111 i searched oracle tutorials couldn't find answer. can explain behavior?
don't forget '++' post-increment operator returns value of j before increment happened. is, if 'j' 7, 'j++' sets j 8, but returns 7. ~7 output saw, number ending in 3 0 bits.
the '++' post-increment operator can operate on so-called "l-values". l-value value exists somewhere code can logically reference -- variable, or array element, parameter or class field. take value of of l-value , apply numerical operation it, r-value. r-values just value, , don't refer persistent storage result put. can assign l-values not r-values -- , if tried '++' r-value, compile error.
if '~' operator went first, you'd ++-ing r-value, in (~j)++. not compile. fact code compiles @ means precedence other way: ~(j++).
parentheses simplest way know of can sort out precedence whenever there confusion: write 3 test cases:
- the original way you're uncertain about.
- with parentheses forcing 1 order of operations.
- with parentheses forcing other order of operations.
run , see whether #2 or #3 produces same result #1. :-)
Comments
Post a Comment