This week's book giveaway is in the Design forum. We're giving away four copies of Building Microservices and have Sam Newman on-line! See this thread for details.

1. byte b1 = (byte)(2 * Byte.MAX_VALUE); I think b1 = 0111 1111 1111 1111 1111 1111 1111 1111 2.byte b2 = -2; for negtive number 1000 0000 0000 0000 0000 0000 0000 0000 binary of 2 is 10 which is equal to 1000 0000 0000 0000 0000 0000 0000 0010 if I invert also because of negtive we should get 0111 1111 1111 1111 1111 1111 1111 1101 How is (b1 == b2).Did I do anything wrong? Thanks.

Hi, b1 will be 11111110 and because it is a byte, it has 8 bits with the most significant bit as 1(that makes it negative). When you do the conversion to decimal,the value is -2. So, b1 == b2 is true. Kavitha

A byte is only 8 bits, not 32 as you are showing here.

Ron Newman - SCJP 1.2 (100%, 7 August 2002)

suresh kamsa
Ranch Hand

Joined: Jul 30, 2001
Posts: 149

posted

0

1. byte b1 = (byte)(2 * Byte.MAX_VALUE); 2. byte b2 = -2; 3. System.out.println(b1 == b2); as per my knowledge MAX_VALUE = 0111 ... 1111 according to that b1 = 0111 1111(most significant seven bits set to 1 and least one bit set to zero) MIN_VALUE = 1000 ... 0000 how b1 becomes -2 here, please explain me in detail.

As you said Byte.MAX_VALUE is 01111111. Now, when you multiply a number by 2, what happens is a shift left by one bit. So, Byte.MAX_VALUE * 2 can be resolved to 01111111 << 1 which gives 11111110 whose value is -2. To be sure, let's take the byte value 2 and make it negative (keyword: 2's complement): 2 is 00000010 to get -2 we invert all bits like this 11111101 and add 1, that is 11111110 As you can see we get the same value... So Byte.MAX_VALUE * 2 is equal to -2

Thanks for your in-detail explanation. Is the same rule applies wheh I multiply number by 3 or 4 etc.(shift left by one bit) eg.(Byte.MAX_VALUE * 3) Is the same rule applies to Short.MAXVALUE,Integer.MAXVALUE etc. If anybody has a chart kind which shows this please pass on to me. What about Byte.MINVALUE,Short.MINVALUE,Integer.MINVALUE etc Is this possible only for Wrapper primitives? Thanks