Why it is -126? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 8

Why it is -126?

int i=130; byte b=(byte)i; System.out.println(b); Output: -126.. Explaination is needed;;

28th Dec 2017, 1:25 PM
Muhd Khairul Amirin
Muhd Khairul Amirin - avatar
1 Answer
+ 4
byte is not equally to a byte array so an integer of 130 is not 10000010 as binary byte is a number class which can represent numbers between -128 and 127. Which creates it's memory size as big as 1 Byte = 8 bit. So if you are at the top of the number class (127) and add one to it the you created a stack overflow and the result is, that your result is -128. So in byte the addition of 127+1 = -128 This means for your example: 130 = 127 +3 = (127 + 1) + 2= -128+2 = -126
28th Dec 2017, 1:37 PM
Andreas K
Andreas K - avatar