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
• Paul Clapham
• Ron McLeod
• paul wheaton
• Devaka Cooray
Sheriffs:
• Jeanne Boyarsky
• Tim Cooke
• Liutauras Vilda
Saloon Keepers:
• Tim Moores
• Tim Holloway
• Stephan van Hulst
• Carey Brown
• Piet Souris
Bartenders:
• salvin francis
• Mikalai Zaikin
• Himai Minh

# how to know the numeric type value after type cast if it exceeds the range

Ranch Hand
Posts: 32
• Number of slices to send:
Optional 'thank-you' note:
Consider the following line of code:
byte x=64;
byte y=5;
byte z= (byte)(x*y);
After execution what is value of z?

1. 320
2. 0
3. 645
4. 64

The answer is 64.Well but how can one calculate it.I have copy pasted from one of javabeat mock tests

Greenhorn
Posts: 13
• Number of slices to send:
Optional 'thank-you' note:
The result of x * y should be a 32 bit int, but the cast tells the compiler to make the result a 8 bit byte instead. Primitive casts are done by lopping off the higher order bits. So, to demonstrate, 320 (the int result of x * y) would be represented as:

00000000 00000000 00000001 01000000

But casting to the byte gets rid of the first 24 bits, leaving

01000000

which is 64!

Sheriff
Posts: 11343
• Number of slices to send:
Optional 'thank-you' note:
When x and y are multiplied, both are promoted to type int, which is the type of the result. As an int, this is 320. To understand what happens to this value when cast to type byte, you need to look at the binary representation. As a 32-bit int, 320 is...

0000 0000 0000 0000 0000 0001 0100 0000

When this is cast to an 8-bit byte, only the 8 bits to the right are retained...

0100 0000

And this represents 64.

marc weber
Sheriff
Posts: 11343
• Number of slices to send:
Optional 'thank-you' note:
Well, David beat me to the post by a few seconds, but we obviously concur.

Ranch Hand
Posts: 162
• Number of slices to send:
Optional 'thank-you' note:
is this on the exam? i dont think bit manipulation is on the exam. can somebody confirm this. Thanks
[ April 09, 2008: Message edited by: sridhar row ]

marc weber
Sheriff
Posts: 11343
• Number of slices to send:
Optional 'thank-you' note:

Originally posted by sridhar row:
is this on the exam? i dont think bit manipulation is on the exam...

Bit manipulation (shifting, bitwise &, |, ^, etc.) is still on the 1.4 exam. It is not on the 1.5 or 1.6 exam.

However, this example is not really bit manipulation -- it's a narrowing cast. I don't know whether you will see this on the more recent exams, but I think you should be prepared for it.

sridhar row
Ranch Hand
Posts: 162
• Number of slices to send:
Optional 'thank-you' note:
Thanks Marc