Originally posted by Jay Patel:
public static void main( String[] args )
{
byte b = 127;
byte c = (byte)(b + 1);
System.out.println(b);
System.out.println(c);
}
When I compile and run this, it displays c as -128. Why is it doing this?
byte b is 127 which is 01111111
how does adding 1 to it gives 10000000.
I am bit confused on this, appreciate your help.
Thanks in advance.
You're getting overflow, bytes can store numbers from -128 to 127.
127=0111 1111
0111 1111
+0000 0001
----------
1000 0000
To read the number apply the 2's complement rules:
1) complement: ~1000 0000 = 0111 1111
2) add 1: 0111 1111 + 1 = 1000 0000
3) read the number: 1000 0000 = 128
4) add the sign and you get: -128.
HTH,
Bojan
[ February 25, 2004: Message edited by: Bojan Knezovic ]