Why is this self-completion equal to 0?

I wonder how fast the add-on will increase, I wrote a quick loop in Java to see:

int count = 1; while(true){ System.out.println(count); count += count; } 

The result was unexpected:

 0 0 0 0 0 ... 

Why is this? count initialized to 1, so internal addition must be done by count + count or 1 + 1 . Why is the result 0?

+5
source share
1 answer

The output you output is the final lines of output, not the first 30-31 lines. This happens so quickly that after the first 31 iterations, it goes beyond INT MAX , and the result of the addition is 0. Remember that a signed integer has a maximum value of 2^31 or 4 signed bytes.

Instead of while(true) { try while(count>0) { you will see the first few iterations when it was not.

+13
source

All Articles