a) public class test {
public static void main(String args[]) {
byte x = 3;
x = (byte)~x;
System.out.println(x);
}
}
The bit value of the byte 3 is
00000011
~ is the complement operator
The result of ~3 is
11111111111111111111111111111100
Casting it to a byte we get
11111100
Which is the representation of -4.
b) public class test {
public static void main(String args[]) {
int x;
x = -3 >> 1;
x = x >>> 2;
x = x << 1;
System.out.println(x);
}
}
The representation of -3 is
11111111111111111111111111111101
The first shift gives
11111111111111111111111111111110
The second shift gives
00111111111111111111111111111111
The third shift gives
01111111111111111111111111111111
The value is
Integer.MAX_VALUE
c) public class test {
public static void main(String args[]) {
int i = -1;
i = i >> 1;
System.out.println(i);
}
}
The bit representation of -1 is
11111111111111111111111111111111
The shift gives
11111111111111111111111111111111
which is -1.
Negative numbers are stored using 2's complement.