Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

+= operator

 
Shiva Mohan
Ranch Hand
Posts: 484
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


result is -126.but i was expecting the answer 130.how the answer -126 came?please explain?
 
Matt Russell
Ranch Hand
Posts: 165
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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).
 
wise owen
Ranch Hand
Posts: 2023
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic