• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

+= operator

 
Ranch Hand
Posts: 486
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


result is -126.but i was expecting the answer 130.how the answer -126 came?please explain?
 
Ranch Hand
Posts: 165
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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).
 
Ranch Hand
Posts: 2023
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 ]
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic