Unexpected output for type int

While studying JAVA, I tried to check the upper limit of the while , which continues to increase int . Please see the following program:

  public class Test { public static int a(){ int a = 10; while(a > 9 ) ++a; return a; } public static void main(String[] argc) { Test t = new Test(); int k = ta(); System.out.println("k = "+(1 * k)); } } 

I know that the 32-bit range is from -2,147,483,648 to 2,147,483,647, therefore, based on this, I expected the output as 2,147,483,647 , but instead I get:

 k = -2147483648 

I even tried

  System.out.println("k = "+(1 * k/2)); 

but still the conclusion:

 k = -1073741824 

Question:

Why is the decision negative when it should be positive?

+5
source share
4 answers

You increase your a int by 1 until you reach 1 + Integer.MAX_VALUE , which shifts its value to -2147483648 == Integer.MIN_VALUE .

Here your loop commented:

 // "infinite" loop as a is assigned value 10 while(a > 9) // when a reaches Integer.MAX_VALUE, it is still incremented by 1 ++a; // loop condition now false, as value for a has shifted to -2147483648 return a; 
+5
source

What happens is called integer overflow .

The maximum 32-bit integer value in binary format:

0111 1111 1111 1111 1111 1111 1111 1111

When you add 1 to this number, you get:

1000 0000 0000 0000 0000 0000 0000 0000

This is a two-component compliment or -2147,483,648. Since any negative number is less than 9, the while loop exits.

+2
source

If we look at Oracle docs for int values, we can find out that:

The operators that work on the int primitive value do not indicate overflow or underflow

Results are determined by the language and independent versions of the JVM :

Integer.MAX_VALUE + 1 is the same as Integer.MIN_VALUE
Integer.MIN_VALUE - 1 is the same as Integer.MAX_VALUE

+1
source

You increase the value until a positive limit is reached, and it becomes all bits, but the sign bit becomes equal to 1.

0x7FFFFFFF = 01111111 11111111 11111111 11111111

This is a binary representation of 2147483647, which is INT_MAX. When you increase it once, it becomes

0x80000000 = 10,000,000,000,000,000,000,000,000,000

which is equal to INT_MIN, -2147483648.

Now

2147483647 is greater than 9, so your cycle continues. Another gain and oops, all of a sudden it's -2147483648, which is less than 9. This is the point at which your loop condition fails.

+1
source

Source: https://habr.com/ru/post/1200836/


All Articles