BagJava | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

BagJava

Please can who explain code? Why output - 128 ? byte by = 1 while(by>0) by++; System.out.println(by);

20th Nov 2017, 6:00 AM
Стрельбицкий Мирослав
Стрельбицкий Мирослав - avatar
1 Answer
+ 3
Imagine you have a computer which has numbers which can have at most three digits, and you start counting in a loop. 1, 2, 3, ..., 999 once you get to 999, something interesting happens: If you add 1, you get 1000. But since your computer can store only three digits, the 1 in front is discarded and you are back at 0. This is called overflow! Something very similar is happening in your case - it's just that the digits are binary, not decimal (0 and 1 only), and the frontmost binary digit (bit) of the number is used to store if it's a positive or negative number; 0 is positive, 1 is negative. So just by counting you will count "into" the sign bit and the number flips into the negatives. For example: 00000000 = 0 00000001 = 1 00000010 = 2 00000011 = 3 01111111 = 127 10000000 = -128 (the leftmost bit is flipped to negative) Negative numbers are stored a bit differently in your computer, so you overflow to -128 instead of -0. (It's called two's complement if you want to look it up) In hope that wasn't too complicated!
20th Nov 2017, 6:35 AM
Schindlabua
Schindlabua - avatar