• Post Reply Bookmark Topic Watch Topic
  • New Topic

Casting question  RSS feed

 
Jorma Rodieck
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Howdy All -

I am prepping for the 803 test and came across this one. Just trying to understand the concept of what is happening.

If a byte can only store values between -128 and 127 ... and you cast a larger int to a byte as below. Why does this print 44?

byte b = (byte) 300;

System.out.println(b);

Thanks.

- Jorma




 
Joanne Neal
Rancher
Posts: 3742
16
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
300 decimal is 100101100 binary
A byte is 8 bits so the cast loses the left hand bit to give 00101100 which is 44 decimal
 
Jorma Rodieck
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ah... I see. Thank you!
 
Campbell Ritchie
Marshal
Posts: 56518
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch

The official name for such phenomena is Narrowing Primitive Conversions that lose information. The link to the Java Language Specification (=JLS) shows such an example. The full explanation will be in that section of the JLS.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!