0

Casting of integer to byte

when I ran the following code - int a=130; byte b= (byte) a; System. out. println(b); //Output. -126. Can anyone explain how?

6th Jan 2018, 5:11 AM
Shalini Jha
Shalini Jha - avatar
2 ответов
+ 3
It seems that the byte type has a range of -128 to 127, as it is signed. So when you assign a number 130 to a byte variable, the variable undergoes overflow and for 128 the output moves to the highest negative number, -128. So when the input is 130, the number overflows to -126 and thus you get the output -126.
6th Jan 2018, 5:25 AM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar
+ 1
Thanks Kinshuk....
6th Jan 2018, 5:26 AM
Shalini Jha
Shalini Jha - avatar