Java arithmetic

Why does this code return the wrong value?

int i=Integer.MAX_VALUE+1;
long l=Integer.MAX_VALUE+1;
System.out.println(l);
System.out.println(i);

Solution

To integer MAX_ When value adds 1, it overflows and wraps around integer MIN_ VALUE.

This happens because Java uses two's complexity to represent integers 4-bit example:

0000 : 0
0001 : 1
...
0111 : 7 (max value)
1000 : -8 (min value)
...
1110 : -2
1111 : -1

So when you add 1 to 0111 (maximum), it becomes 1000, which is the minimum Extending this idea to 32 bits works the same way

As for why your long also displays incorrect results, this is because it performs addition on int and implicitly converts it to long You need to do this:

long l = (long) Integer.MAX_VALUE + 1
System.out.println(l); // Now prints the correct value
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>