+ 1
Why answer is -2?
public class Program { public static void main(String[] args) { byte a=127; a+=127; System.out.print(a); } }
1 Answer
+ 14
01111111 is the binary representation of 127
If you add 127, you obtain :
11111110
It would be alright if the byte was unsigned, BUT as it is signed, you'll obtain a negative number as the first bit is 1
To know the value of a negative number, you need to take its value as a positive and do a little trick. Let's use 2 as an example (coincidence ? :p)
2 is represented like that :
00000010
Then, you need to toggle each bit, you obtain :
11111101
And finally, do the binary addition of 1 to the previous result. You obtain :
11111110 == 127+127