简体   繁体   中英

Why does incrementing a Java int eventually result in a negative number?

I was trying to check different inputs and creating infinite loops in java and I found that once the int is getting incremented over the maximum limit it turns in to negative -2147482958 . I am just increasing the int in infinite loop...

Code:

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

The last to value gets printed out is,

2147483337
-2147482958

Now, Why does it goes to negative?

Why does it goes to negative?

Because that is what is specified to happen in Java when an int calculation overflows.

JLS 15.18.2

"If an integer addition overflows, then the result is the low-order bits of the mathematical sum as represented in some sufficiently large two's-complement format. If overflow occurs, then the sign of the result is not the same as the sign of the mathematical sum of the two operand values."


(This doesn't explicitly say that overflow always gives a negative number. And it doesn't always. But if you apply the rule, it does explain why incrementing Integer.MAX_VALUE by +1 gives you Integer.MIN_VALUE ...)

According to the documentation:

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

So when you add one to an integer's max value:

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

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

To use larger integers, use a long instead which has 64 bits .

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

See the docs :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM