aspose file tools*
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
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "+= operator" Watch "+= operator" New topic
Author

+= operator

Shiva Mohan
Ranch Hand

Joined: Jan 05, 2006
Posts: 479


result is -126.but i was expecting the answer 130.how 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.

http://www.particle.kth.se/~lindsey/JavaCourse/Book/Part1/Tech/Chapter02/integers.html

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


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

Joined: Feb 02, 2006
Posts: 2023

b+=3;

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: http://aspose.com/file-tools
 
subject: += operator