+ 7

How output is 126?

int i =130; byte b = (byte)i; System.out.print(b); //Output is -126 šŸ˜¢

18th Jan 2018, 2:50 PM
Rishabh
Rishabh - avatar
4 Answers
+ 24
ok , let me add to the answer above ā˜ŗ //range of byte will be from -2^7 to 2^7 that is -128 to 127 , since 132 can't come in this range ... to bring 132 in this range , substraction of 256 will be done ... ie 132 -256 = -126 //thats the fast approach especially when n belongs to [128 to 256] //but there is an general approach , in which u have to convert the decimal number to binary format & since byte can hold only 8 bits ... so take only right most 8 digits & check if left most bit is 0 , nothing u have to do ... just convert that back to decimal ... if left most bit is 1 , then -1 to that binary number & then take 1's complement (replacing 1 by 0 & vice versa) & then convert it back to decimal system & put sign as -ve (bcz of 1 in left most digit) //thats the general approach //btw i searched for some good approach & got to know 2 - 3 interesting thingsšŸ‘Œ more excluding it šŸ˜‚ā˜ŗ ... yeahhh!!!!
18th Jan 2018, 5:57 PM
Gaurav Agrawal
Gaurav Agrawal - avatar
18th Jan 2018, 2:57 PM
Gaurav Agrawal
Gaurav Agrawal - avatar
+ 5
You should read about the data types deeper. Also about the binary numbers and their representations. byte is 8 bit data type. It means that you have 256 possible bit combinations for the numbers. And more specific from -128 to 127, because the leading bit is for the sign of the number (0 for positive, 1 for negative). Since it's not possible to put 130, in byte, here is what happens: 127 + 1 -> -128 127 + 2 -> -127 127 + 3 -> -126
18th Jan 2018, 4:50 PM
Boris Batinkov
Boris Batinkov - avatar
+ 4
@gaurav that's not clear 2 me plz can you explain it...by taking the above as example?
18th Jan 2018, 3:47 PM
Rishabh
Rishabh - avatar