i have extracted the following para from K&B
byte a = (byte) 128;
But then what�s the result? When you narrow a primitive,
Java simply truncates the
higher-order bits that won�t fit. In other words, it loses all the bits to the left of the
bits you�re narrowing to.
Let�s take a look at what happens in the preceding code. There, 128 is the bit
pattern 10000000. It takes a full 8 bits to represent 128. But because the literal
128 is an int, we actually get 32 bits, with the 128 living in the right-most
(lower-order) 8 bits. So a literal 128 is actually
00000000000000000000000010000000
Take our
word for it; there are 32 bits there.
To narrow the 32 bits representing 128, Java simply lops off the leftmost
(higher-order) 24 bits. We�re left with just the 10000000. But remember that a
byte is signed, with the leftmost bit representing the sign (and not part of the value
of the variable). So we end up with a negative number (the 1 that used to represent
128 now represents the negative sign bit). Remember, to find out the value of a
negative number using two�s complement notation, you flip all of the bits and then
add 1. Flipping the 8 zeroes give us: 01111111, and adding 1 to that gives us
10000000, or back to 128! And when we apply the sign bit, we end up with -128.
I don't understand fully the above paragraph...i read it many times....
how 10000000 it is -128 ... is because 0 is only positive but if its then how we can say that it is negative -128... so it means.. that leftmost bit one is also included while counting number as well as sign bit ???
then how the one question has such answer like
Q ..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
its answer is "d"
with explanation like....
Bytes are stored as 8 bit two's complement signed integers. When an int primitive is cast to a byte, the three most significant bytes are discarded and only the least significant byte remains. The most significant bit of the remaining byte becomes the new sign bit. byte a = (byte)127; // 01111111. byte b = (byte)128; // 10000000. byte c = (byte)255; // 11111111. byte d = (byte)256; // 00000000.
but how in above... 11111111 is -1 00000000 is 0
please explain me
so in one question of dann examm