java - Shifting a type char, similar assignments behave differently -


hi have piece of java code shifts character 2, so

char ch = 'a'; ch += 2; system.out.println(ch); 

the output in case 'c' (as expected). if rewrite code this:

char ch = 'a'; ch = ch + 2; system.out.println(ch); 

i compilation error 'type mismatch: cannot convert int char'. why happening, aren't 2 assingments equal?

it's common misconception x += y identical x = x + y. jls §15.26.2:

a compound assignment expression of form e1 op= e2 equivalent e1 = (t) ((e1) op (e2)), t type of e1, except e1 evaluated once.

notice there implicit cast involved. when have like:

ch = ch + 2;  // no cast, error 

the type of right-hand side int while type of left-hand side char, there type mismatch between 2 sides of assignment, hence error. can fixed explicit cast:

ch = (char) (ch + 2);  // cast, no error 

Comments

Popular posts from this blog

php - Magento - Deleted Base url key -

javascript - Tooltipster plugin not firing jquery function when button or any click even occur -

java - WrongTypeOfReturnValue exception thrown when unit testing using mockito -