When the value exceeds the range, the maximum value becomes the minimum value, and the minimum value becomes the maximum value, and when the assigned value exceeds the range, an error will be reported directly and the operation cannot be performed. The out-of-range form is only possible in the form of addition or subtraction.
//基本数据类型超出范围
/*
1.byte :-128~127(-2的7次方~2的7次方-1)
2.short :-32768~32767(-2的15次方~2的15次方-1)
3.int :-2147483648~2147483647(-2的31次方~2的31次方-1)
4.long :-9223372036854774808~9223372036854774807(-2的63次方~2的63次方-1)
5.float:3.402823e+38~1.401298e-45和-3.402823e+38~-1.401298e-45 (e+38 表示乘以10的38次方,而e-45 表示乘以10的负45次方)
6.double:1.797693e+308~4.9000000e-324和-1.797693e+308~-4.9000000e-324(同上)
* */
public void a(){
// 如果是赋值时超出范围会直接报错、如果是运行是进行加减导致超出范围最大值变为最小值,最小值变为最大值。
byte b1=127; // 8字节,-128~127
byte b2=-128;
short s1=32767;
short s2=-32768;
int i1=2147483647;
int i2=-2147483648;
byte j=2;
for (int i=0;i<2;i++){
b1++;
b2--;
s1++;
s2--;
i1++;
i2--;
System.out.println("byte(max):"+b1+" byte(min) "+b2);
System.out.println("short(max):"+s1+" short(min) "+s2);
System.out.println("int(max):"+i1+" int(min) "+i2);
}
}
结果:
byte(max):-127 byte(min) 127
short(max):-32768 short(min) 32767
int(max):-2147483648 int(min) 2147483647
byte(max):-125 byte(min) 126
short(max):-32767 short(min) 32766
int(max):-2147483647 int(min) 2147483646