I am a newbie in programming. I was studying from a Java object programming book and performing the tutorials and examples on the book simultaneously on computer. In the book it says that the maximum and minimum value of integers are;
Integer.MAX_VALUE = 2147483647
Integer.MIN_VALUE = -2147483648
So OK. there is no problem here but; it says that if we add 1 to the maximum value and subtract 1 from minimum;
class test {
public static void main(String[] args) {
int min = Integer.MIN_VALUE -1;
int max = Integer.MAX_VALUE +1;
int a = min - 1;
int b = max + 1;
System.out.println("min - 1 =" + a);
System.out.println("max - 1 =" + b);
}
}
thus we find;
min - 1 = 2147483646
max + 1 = -2147483647
and it says that this result is because that the binary process in memory which is limited with 32 bit. The thing that I couldn't understand. In the piece of code isn't it adding and subtracting 2 respectively from maximum and minimum values?;
int min = Integer.MIN_VALUE -1; // subtracted 1 here
int max = Integer.MAX_VALUE +1; // added 1 here
int a = min - 1; // subtracted 1 here
int b = max + 1; // added 1 here
Note that a
is Integer.MAX_VALUE - 1
and b
is Integer.MIN_VALUE + 1
. So yes, it is indeed subtracting and adding 1 twice in each case. The book is not wrong, but it's a stupid way of teaching about wrap-around overflow. Just printing Integer.MIN_VALUE - 1
and Integer.MAX_VALUE + 1
would have made the point.
int min = Integer.MIN_VALUE -1; // min is set to Integer.MAX_VALUE by underflow
int max = Integer.MAX_VALUE +1; // max is set to Integer.MIN_VALUE by overflow
From the Java Language Specification, §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.
The JLS is the ultimate authority when it comes to questions like this, but I don't recommend reading it as a way to learn Java. You'd be better off going through the Java Language Tutorial . It's fairly comprehensive and the content is very high quality.
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.