• 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

Casting question

 
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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




 
Rancher
Posts: 3742
16
  • Likes 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Ah... I see. Thank you!
 
Marshal
Posts: 79177
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
reply
    Bookmark Topic Watch Topic
  • New Topic