This week's book giveaway is in the OCAJP 8 forum.
We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes += operator Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of OCA Java SE 8 Programmer I Study Guide this week in the OCAJP 8 forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "+= operator" Watch "+= operator" New topic

+= operator

Shiva Mohan
Ranch Hand

Joined: Jan 05, 2006
Posts: 481

result is -126.but i was expecting the answer the answer -126 came?please explain?
Matt Russell
Ranch Hand

Joined: Aug 15, 2006
Posts: 165
Bytes are 8-bit signed integers, and so they store values between -128 and 127. If you do arithmetic that goes over 127, it loops back round to the negative end.

(Quite why it doesn't throw some sort of overflow error, I don't know).

Inquisition: open-source mock exam simulator for SCJP and SCWCD
wise owen
Ranch Hand

Joined: Feb 02, 2006
Posts: 2023


will translate to

b =(byte)(b + 3);

Note, since the compiler does the implicit conversion without warning, you need to pay attention when using the compound-assignment operator. Some of the conversions are Narrowing conversions, just like in the last example, from an int to a byte. Narrowing conversions may lose information about the overall magnitude of a numeric value and may also lose precision.

What is the result of 'byte x = 100; x += 100;'?
[ October 07, 2006: Message edited by: wise owen ]
I agree. Here's the link:
subject: += operator
It's not a secret anymore!