从JDK1.0开始,Integer中就定义了MIN_VALUE
和MAX-VALUE
两个常量:
/**
* A constant holding the minimum value an {@code int} can
* have, -2<sup>31</sup>.
*/
public static final int MIN_VALUE = 0x80000000;
/**
* A constant holding the maximum value an {@code int} can
* have, 2<sup>31</sup>-1.
*/
public static final int MAX_VALUE = 0x7fffffff;
Q1:谁能给解释一下,这两个常量为什么会分别定义成0x80000000
和0x7fffffff
。
Q2:java.lang.String
的最大长度是多少?
Q3:如下代码能抛出异常吗?为什么
int x = Integer.MAX_VALUE+10;
if(x >= Integer.MAX_VALUE || x <= Integer.MIN_VALUE){ //throw exception}
Q1:
The signed number of the four-byte integer is -2^31~2^31-1 (also written in the comments of MIN_VALUE and MAX-VALUE). It will be clear after checking the two's complement binary representation of the corresponding boundary
Q2:
I don’t use Java much, so I’m not sure. It should be very long. Attached are the key fields of String
Q3:
int x = Integer.MAX_VALUE 10;
x overflows, x is actually-2^31 9
, the if condition is not true, and no exception will be thrown.Q1: What the computer can understand is the binary string of 01. The binary representation of numerical values within the computer includes positive code, complement code and complement code. Generally, two's complement is used for representation and operations.
MIN_VALUE = 0x80000000
andMAX_VALUE = 0x7fffffff
are the minimum value (-2^31) and maximum value (2^31-1) of Integer expressed in complement. As for why the two's complement representation is used, simply speaking, it is to facilitate calculations. For details, you can Google it yourself or look up this basic textbook. As for why the maximum and minimum values of Integer are these two numbers, this is because the Java language specification stipulates that the int type is 4 bytes, whether it is a 32/64-bit machine, this is the basic part of its claimed cross-platform.Q2: The maximum length of a String depends on its internal data representation. String is represented internally by a char array. The length of the array is limited in Java to the maximum value that can be represented by an int type, which is
MAX_VALUE = 0x7fffffff
in Q1. This is reflected by its internal properties representing offsetint offset
and lengthint count
.Q3: The above code will not throw an exception. For values outside the representation range, the strategy adopted is the truncation effect, that is, the low bits are directly intercepted and the high bit information that is out of the range is discarded. This is the so-called overflow. For example, if the int type operation result exceeds the representation range, the lower 32 bits (4 bytes in Q1) are directly intercepted as the operation result. As a result, the first line of the above code will overflow, and the overflow result will cause the condition of the second line to be false.