8大基本数据类型
byte
byte:8位,存放的数据范围是-128~127之间,默认值为0。
short
short:16位,数据范围是-32768~32767之间,默认值为0。
int
int:32位,数据范围是-2^31 ~2^31-1,默认值为0。
long
long:64位, 数据范围为-2^63 ~2^63-1,默认值为0L。
float
float:32位,数据范围在3.4e-45~1.4e38,直接赋值时必须在数字后加上f或F,默认值为0.0f。
double
double:64位,数据范围在4.9e-324~1.8e308,赋值时可以加d或D也可以不加,默认值为0.0。
boolean
boolean:只有true和false两个取值,默认值为false。
char
char:16位,存储Unicode码,用单引号赋值,默认值为\u0000(空字符)。
类型名称 |
字节 |
最小值 |
最大值 |
默认值 |
举例 |
包装类 |
byte |
1 |
-128(-2^7) |
127(2^7-1) |
0 |
byte a=10; |
Byte |
short |
2 |
-32768(-2^15) |
32767(2^15 - 1) |
0 |
short b=20; |
Short |
int |
4 |
-2,147,483,648(-2^31) |
2,147,483,647(2^31 - 1) |
0 |
int c=200; |
Integer |
long |
8 |
-9,223,372,036,854,775,808(-2^63) |
9,223,372,036,854,775,807(2^63-1) |
0L |
long d=10L; |
Long |
float |
4 |
3.4e-45 |
1.4e38 |
0.0f |
float e=10.0f; |
Float |
double |
8 |
4.9e-324 |
1.8e308 |
0.0 |
double f=0.0; |
Double |
char |
2 |
\u0000(即为0) |
\uffff(即为65,535 |
0 |
char c=‘a’; |
Character |
boolean |
返回true和false两个值 |
这种类型只作为一种标志来记录true/false 情况 |
只有两个取值:true 和 false |
false |
boolean flag=true; |
Boolean |
如何选择数据类型
- 如果要表示整数就使用int,表示小数就使用double;
- 如果要描述日期时间的毫秒数或者表示文件的大小就用long;
- 如果要实现内容的传递或者编码的转换使用byte;
- 如果要实现逻辑控制,可以使用boolean;
- 如果要使用中文,推荐使用char避免中文乱码问题;
为什么要有包装类
为了让基本类型也具有对象的特征,就出现了包装类型(例如如在使用集合类型Collection类时就一定要使用包装类型而非基本类型)因为容器都是装Object的,这是就需要这些基本类型的包装器类了。
自动装箱和自动拆箱
自动装箱:将基本数据类型自动转换为引用数据类型
int x=2;
Integer i=x;
本质是调用了Integer中的valueOf方法
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)//low=-128,high=127
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
}
自动拆箱:将引用数据类型自动转换为基本数据类型
Integer i=2;
int x=i;
本质是调用了Integer的intvalue方法
public int intValue() {
return value;
}
两者的区别
- 声明方式的不同:基本类型不使用new关键字,而包装类型需要使用new关键字。
- 存储位置不同:基本类型是直接将变量值存储在栈中,而包装类型是将对象放在堆中。
- 初始值不同:基本类型的初始值如int为0,而包装类型的初始值为null;
- 使用方式不同:基本类型直接赋值直接使用就好,而包装类型在集合时会使用到。
练习1
public class Main {
public static void main(String[] args) {
Integer i1 = 124;
Integer i2 = 124;
Integer i3 = 234;
Integer i4 = 234;
System.out.println(i1==i2);
System.out.println(i3==i4);
}
}
运行结果
true
false
原因
在通过valueOf方法创建对象时,如果数值在[-128,-127]之间则返回Integer中已经存在的对象引用,
否则创建一个新的对象。在Integer中有一个静态内部类IntegerCache,在类中定义了Integer数组cache[],
该数组存储了-128~127里的所有整数。
上面i1和i2在范围内,所以指向的是同一个对象,而i3和i4不在范围内,新创建了一个对象,即Integer i3 = 234;
相当于Integer i3=new Integer(234);Integer i4 = 234; 相当于Integer i4=new Integer(234);指向的是不同的对象。
练习2
public class Main {
public static void main(String[] args) {
Double i1 = 124.0;
Double i2 = 124.0;
Double i3 = 234.0;
Double i4 = 234.0;
System.out.println(i1==i2);
System.out.println(i3==i4);
}
}
结果
false
false
原因
在某个范围内的整型数值的个数是有限的,而浮点数却不是。所以Double中并没有定义像Integer存储数据的数组。