基本数据类型:
byte | short | int | long | float | double | char | boolean | |
byte[字节] | 1 | 2 | 4 | 8 | 4 | 8 | 2 | 1 |
bit[位] | 8 | 16 | 32 | 64 | 32 | 64 | 16 | true/false |
-128~127 | -2^15-2^15-1 | -2^31-2^31-1 | -2^63-2^63-1 | 4字节 float类型的数值有一个后缀 f (例如:3.0f ) | 8字节 没有后缀F的浮点数值(如3.14)默认为double类型 | 2字节 | 1字节 范围:true、false | |
默认值初始化值 | 0 | 0 | 0 | 0 | 0.0 | 0.0 | \ | false |
※小可转大,大转小失精度需要用到强制转换;
例如:(1)int a=12;double b=a;(2)double a=3.0;int b=(int)a;
引用数据类型:
默认值 | |
数组 | null |
类 | null |
接口 | null |
基本数据分配在栈上;
引用数据类型分配在堆上;
※String类型,String是项目中必不可少且使用最多的数据类型,它属于引用数据类型中“类”的范畴。
不论是基本数据类型还是引用数据类型,都会在栈中分配一块内存;
对于基本数据来说,这块区域包含的失基本类型的内容;
对于引用数据类型来说,这块区域包含的是指向真正内容的指针,真正的内容被分配在堆上。
基本数据类型的封装类:
原始类型 | 包装类型 |
short(短整型) | Short |
int(整型) | Integer |
long(长整型) | Long |
float(浮点型) | Float |
double(双精度浮点型) | Double |
byte(字节型) | Byte |
char(字符型) | Character |
boolean(布尔型) | Boolean |
包装类的作用:
①提供:字符串、基本数据类型,对象之间互相转化的方式;
例如String跟int的互相转化:
String a = "21";int b = Integer.parseInt(a);//String 转int。
int a = 21; String b = String.valueOf(a);//int转String。
②包含每种基本数据类型的相关属性,如:最大值、最小值等;
延伸:
int和Integer的区别:
1、Integer是int的包装类,int则是java的一种基本数据类型 ;
2、Integer变量必须实例化后才能使用,而int变量不需要 ;
3、Integer实际是对象的引用,当new一个Integer时,实际上是生成一个指针指向此对象;而int则是直接存储数据值 ;
4、Integer的默认值是null,int的默认值是0;
1、由于Integer变量实际上是对一个Integer对象的引用,所以两个通过new生成的Integer变量永远是不相等的(因为new生成的是两个对象,其内存地址不同)。
Integer i = new Integer(100);
Integer j = new Integer(100);
System.out.print(i == j); //false
2、Integer变量和int变量比较时,只要两个变量的值是向等的,则结果为true(因为包装类Integer和基本数据类型int比较时,java会自动拆包装为int,然后进行比较,实际上就变为两个int变量的比较)
Integer i = new Integer(100);
int j = 100;
System.out.print(i == j); //true
3、非new生成的Integer变量和new Integer()生成的变量比较时,结果为false。(因为非new生成的Integer变量指向的是java常量池中的对象,而new Integer()生成的变量指向堆中新建的对象,两者在内存中的地址不同)
Integer i = new Integer(33);
Integer j = 33;
System.out.print(i == j); //false
4、对于两个非new生成的Integer对象,进行比较时,如果两个变量的值在区间-128到127之间,则比较结果为true,如果两个变量的值不在此区间,则比较结果为false
Integer i = 100;
Integer j = 100;
System.out.print(i == j); //true
//========================================================
Integer i = 128;
Integer j = 128;
System.out.print(i == j); //false
如果有错误的地方,还请指正。
参考:
https://www.cnblogs.com/guodongdidi/p/6953217.html