Question: (Check all correct answers) 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? Ada
Mapraputa Is
Leverager of our synergies
Sheriff
Joined: Aug 26, 2000
Posts: 10065
posted
0
I think c and d are correct, since range for byte is -128 to 127.
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
Joined: Aug 28, 2000
Posts: 14
posted
0
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."