• Post Reply Bookmark Topic Watch Topic
  • New Topic

what is special about +=  RSS feed

 
kayanaat sidiqui
Ranch Hand
Posts: 122
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hey guys please tell me the reason--
let byte b =10;
now,
b=b+20;-- compile time error
b+=20;-- but it is not compile time error. why?
 
Ankit Garg
Sheriff
Posts: 9610
37
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
when you use compound assignment operators(+=, -=, *=, /=), cast is not required. But when you use simple unary operators like +, -, *, /. then all the operands are converted to int if they are byte, short, or char.

this is why byte+=byte is ok but byte = byte + byte will result in an error as byte + byte will become int + int and byte = int + int will need a cast
 
Campbell Ritchie
Marshal
Posts: 56553
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to JavaRanch

The special thing about += is that it is a widening and narrowing conversion. If you are feeling brave, have a look at the Java Language Specification, but it is not easy reading.
It is possible to get peculiar results if the intermediate calculation overflows the range of the result variable (which is left of the = sign).
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!