File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Why does Byte do this? Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Reply Bookmark "Why does Byte do this?" Watch "Why does Byte do this?" New topic
Author

Why does Byte do this?

Shanna Ripley
Greenhorn

Joined: Mar 12, 2010
Posts: 18
Hi All,

I was doing a little test program...multiplying a byte, initialised to 1, by 8. I print out the result after each multiplication.
The results are:
2
4
8
16
32
64
-128
0

Can anyone tell me why the seventh value is -128 (why minus?) and the eighth is 0??
I know the Byte ranges from -128 to 127....I'm guessing that has something to do with it.

Thanks in advance
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 16684
    
  19

Shanna Ripley wrote:Can anyone tell me why the seventh value is -128 (why minus?) and the eighth is 0??
I know the Byte ranges from -128 to 127....I'm guessing that has something to do with it.


Short answer. The number overflowed.

For the longer answer why the numbers are -128 and then zero -- google for "twos complement", which is the format used to represent signed numbers in Java.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 9943
    
    6

The top bit is used for the sign. So, when you get to 128, the bit pattern would be
1000 0000

The first bit tells us the answer is negative, then we use 2's complement to figure out the value. When you next double that, you would have

1 0000 0000

but the leading 1 gets chopped off and lost forever, leaving you with 0.


Never ascribe to malice that which can be adequately explained by stupidity.
Shanna Ripley
Greenhorn

Joined: Mar 12, 2010
Posts: 18
Thanks Henry and Fred
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Why does Byte do this?
 
Similar Threads
byte type
Why the result of (byte)(-128) is -128
int value cast to byte
Conversion of Primitives
cast to bytes