Java基本类型和包装类(一)
java有8个基本类型,但是它们不具备面向对象的特性所以不能直接参与面向对象开发,
那么在实际使用上会出现很多的不便为此java为8个基本类型提供了对应的包装类,
以便于让基本类型以对象形式存在并参与面向对象的开发中
基本类型 |
占用空间(位) |
包装类 |
默认值 |
取值范围 |
byte(位) |
8 |
Byte |
0 |
-128~127 |
short(短整数) |
16 |
Short |
0 |
-32768~32767 |
int(整数) |
32 |
Integer |
0 |
-2147483648~2147483647 |
long(长整数) |
64 |
Long |
0l |
-9223372036854775808~9223372036854775807 |
float(单精度) |
32 |
Float |
0.0f |
1.4E-45~3.4028235E38 |
double(双精度) |
64 |
Double |
0.0 |
4.9E-324~1.7976931348623157E308 |
char(字符) |
16 |
Character |
空 |
0~65535 |
boolean |
8 |
Boolean |
flase |
true或false |
推荐使用静态方法valueOf将基本类型转换为包装类
public static Double valueOf(double d) {
return new Double(d);
}
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
Integer i1 = Integer.valueOf(128)
Integer i2 = Integer.valueOf(128)
System.out.println(i1==i2)
Double i3 = Double.valueOf(127)
Double i4 = Double.valueOf(127)
System.out.println(i3==i4)
intValue doubleValue floatValue等 可以将当前包装类表示的数字转换为对应的基本类型推
double d1 = i1.doubleValue();
byte d2 = i1.byteValue();
JDK1.5之后推出了一个新的特性:自动拆装箱.该特性是编译器认可的,会在编译器自动将基本类型与对应的包装类互相转换,省去麻烦.
Integer i = 1;
int a = i;