Hello Amit,
Let me find an easy way to find a solution to your query.
size of byte = 8 bits
range of byte = -128 to 127
Since byte is a signed primitive, the MSB is the signed bit, which means that if the MSB is '1', then the number being represented is a negative number.
So, only 7 bits are required to represent the complete range of byte and MSB is used for indicating, if the number is positive or negative.
So far so good, now lets handle your question:
lets represent 128 in binary format : 10000000
As, i have explained earlier, that in byte if the MSB is '1', then it is a negative number.
now to represent 10000000 in decimal, we have to flip all the bits and add 1 to it (As it is a negative number) 01111111+1 = 10000000 = -128
Lets now solve your question:
Question 8
class Magenta {
static byte a = (byte)127, b = (byte)128, c = (byte)255, d = (byte)256;
public static void main(String args[]) {
System.out.print(a + " " + b + " " + c + " " + d);
}}
What is the result of attempting to compile and run the program?
a. Prints: 127 128 255 256
b. Prints: 127 128 255 0
c. Prints: 127 -1 -127 0
d. Prints: 127 -128 -1 0
e. Run-time error
f. Compile-time error
g. None of the above
a = byte(127) = 127, as this number is in range of byte.
b = byte(126) = -128, as explained above
c = byte(255) = 011111111 (byte representation). Now as byte can hold only 8 bits, we chop off the MSBs. So the resulting representation is 1111111. Now, since the MSB is '1', it is a negative number, so we flip all the bits and add 1 ==> 00000000 + 1 = 00000001. So, as it was a negative number, we get the answer as -1.
d = byte(256) = 100000000 (Byte representation).Now as byte can hold only 8 bits, we chop off the MSBs. So the resulting representation is 00000000. So, the answer is 0. Hence, the result is 0
Therefore 'd' is the correct answer.
I hope that new i am able to solve your query.
-Anu