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

Greenhorn
Posts: 23
• Number of slices to send:
Optional 'thank-you' note:
Which of these attempts to assign a value to a byte primitive variable is out of the byte range?
a. byte b=(byte)255;
b. byte b=(byte)128;
c. byte b=(byte)-128;
d. byte b=(byte)127;
I think none of them is a correct answer. After casting, (byte)255 and (byte)128 should be zero value, because they lost their higher bits. Correct?

Leverager of our synergies
Posts: 10065
• Number of slices to send:
Optional 'thank-you' note:
I think c and d are correct, since range for byte is -128 to 127.

Greenhorn
Posts: 14
• Number of slices to send:
Optional 'thank-you' note:

The result that you will get is
a. byte b=(byte)255; (value will be -1)
b. byte b=(byte)128; (value will be -128)
c. byte b=(byte)-128; (value will be -128)
d. byte b=(byte)127; (value will be 127)
So from this the answer is (a) & (b).

Sachin Kombrabail
Greenhorn
Posts: 14
• Number of slices to send:
Optional 'thank-you' note:

The result that you will get is
a. byte b=(byte)255; (value will be -1)
b. byte b=(byte)128; (value will be -128)
c. byte b=(byte)-128; (value will be -128)
d. byte b=(byte)127; (value will be 127)
So from this the answer is (a) & (b).
The reason why this happens is given with examples in the JLS.
"The results for byte and short lose information about the sign and magnitude of the numeric values and also lose precision. The results can be understood by examining the low order bits of the minimum and maximum int. The minimum int is, in hexadecimal, 0x80000000, and the maximum int is 0x7fffffff. This explains the short results, which are the low 16 bits of these values, namely, 0x0000 and 0xffff; it explains the char results, which also are the low 16 bits of these values, namely, '\u0000' and '\uffff'; and it explains the byte results, which are the low 8 bits of these values, namely, 0x00 and 0xff."