Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

pls explain?

 
vikram choudhary .
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
byte i= (byte)129;
System.out.println(i);

output: -127 why?
can anyone explain?
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As an int, 129 has the following bit representation

00000000000000000000000010000001

When you cast to a byte, you only have the last 8 bits.

So you have the byte

10000001

Because the first bit is a 1, this is a negative number.

To find out what number it is the negative of, flip all the bits and add 1

You get

01111111

So the number is -127.
 
Chandra Bhatt
Ranch Hand
Posts: 1710
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Good Keith!!!



Thanks,
cmbhatt
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic