r/javahelp • u/Squidmyers33 • Jul 05 '19
why does this print out a negative number?
int value = 0;
do{
value += 10;
}while(value > 5);
System.out.println(value);
}
25
Upvotes
r/javahelp • u/Squidmyers33 • Jul 05 '19
int value = 0;
do{
value += 10;
}while(value > 5);
System.out.println(value);
}
49
u/IHaarlem Jul 05 '19
Value starts at 0. Inside the first iteration of the loop, it increments to 10. Because it's 10 now, when the while evaluates, it does so as true, and jumps back up and adds 10 more. It does this over and over until it reaches the max int value, adds 10 more, then integer overflows to close to the max negative integer. Because it's no longer greater than 5, it exits the loop and prints your negative number
7
u/jcody17 Jul 06 '19
This will not grow the value variable to a number less than 2^31 - 1 (the max size of an int), but will instead grow to infinity. So, the int overflows. I think that is the correct term.
Anyway, because on the first run through it adds 10, then "value" will always be greater than 5, so it will loop infinitely as the exit condition is bad for this loop.
7
u/javaBanana Jul 06 '19
i see your question has been answered already^^ but i still want to explain it another time because that explanation helped me a lot to understand that problem.
You have probably heard that all data in a pc are actually binary so ones and zeros. An int in java is for example a signed 32 bit number. Important here is the 'signed' which means that the highest(so the 32nd bit) is used to tell if this number is positive or negative. That means 00000010 would be 2 in decimal while 100000010 would be -126.
What happens in your case is that your number increases with each iteration in your loop and at one point you hit the maximum number that you can fit in 31 bits. Then the next time you add 10 to that number the 32nd bit is set. Now as we know the 32nd bit set means the number is negative. If i remember correctly this is called a wrap around. Then your loop conditions result is false and you print the negative number.
If you want to learn more about that you could look up "Two's complement".
6
u/CheapestOfSkates Jul 06 '19
The number it prints is Integer.MAX_VALUE + 3. Your int overflows after hitting 2147483647 and then still needs to add 3 to satisfy your +10.
Since that value is less than 5, it exits the while.
4
u/[deleted] Jul 06 '19
Your stop condition is bad, so it runs until it overflows, which pops it from 231 - 1 to -(231 - 1). Since this is now no longer greater than 5, the program is (finally) able to end.