Why does Java int increment end up with a negative number?

I was trying to test different inputs and create infinite loops in java and I found that after it int

gets incremented over the max limit it goes negative -2147482958

. I just increment int in an endless loop ...

Code:

public static void infiniteLoop(){
        for(int i=0;i>-1;i++){
            i = i + 1000;
            System.out.println(i);
        }
    }

      

The last value will be printed,

2147483337
-2147482958

      

Now why is this going negative?

+2


source to share


4 answers


Why is this going negative?

Because that's what Java says when computation overflow int

.

JLS 15.18.2



"If integer sums are merged, then the result is the least significant bits of the sum, represented in some sufficiently large two's complement format. If an overflow occurs, the sign of the result does not match the sign of the sum of the two operand values.


(It does not explicitly say that the overflow always yields a negative number, and it is not always possible. But if you apply the rule, it explains why the increment Integer.MAX_VALUE

on +1

gives you Integer.MIN_VALUE

...)

+8


source


Because when the int value reaches Integer.MAX_VALUE , incrementing it causes an overflow and therefore wraps around Integer.MIN_VALUE .



To use large integers, use long , which is 64 bits .

+3


source


According to the documentation:

The int data type is a 32-bit two-digit integer. It has a minimum value of -2147,483,648 (0x80000000) and a maximum value of 2,147,483,647 (0x7FFFFFFF) (inclusive)

So when you add one to the maximum integer value:

0x7FFFFFFF + 0x00000001 = 0x80000000 (-2,147,483,648)

+3


source


Because it int

ranges from -2,147,483,648 to 2,147,483,647. Hence, once it reaches its upper limit, it overflows and starts out negative.

See the docs :

The int data type is a 32-bit two-digit integer. It has a minimum value of -2147,483,648 and a maximum value of 2,147,483,647 (inclusive)

+1


source







All Articles