概念
Java中的基本数据类型没有方法和属性,而包装类就是为了让这些拥有方法和属性,实现对象化交互。
注:本讲以Integer为例,其他七种类型类似。
基本类型和包装类型对应关系:
数值型包装类都继承至Number。
基本数据和包装类之间的转换
装箱:基本数据类型转换为包装类。
拆箱:包装类转换为基本数据类型。
public class Test3 {
public static void main(String[] args) {
//自动装箱
Integer t2 = 1;
//手动装箱
Integer t3=new Integer(1);
//自动拆箱
int t4=t2;
//手动拆箱
//通过intValue()方法返回int值,还可以利用其他方法装换为其他类型
int t5=t2.intValue();
}
}
字符串与数据类型转换
- 通过包装类Integer.toString()将整型转换为字符串;
- 通过Integer.parseInt()将字符串转换为int类型;
- 通过valueOf()方法把字符串转换为包装类然后通过自动拆箱。
public class Test3 {
public static void main(String[] args) {
//基本数据类型转换为字符串
String t2 = Integer.toString(5);
String t3 = 5 + "";
//字符串转换为基本数据类型
int t4 = Integer.parseInt(t2);
//通过valeOf,先把字符串转换为包装类然后通过自动拆箱
int t5 = Integer.valueOf(t2);
}
}
包装类知识
-
包装类对象的初始值为null(是一个对象);
-
包装类对象之间的比较:
public class Test3 {
public static void main(String[] args) {
Integer one=new Integer(100);
Integer two=new Integer(100);
one和对two是两个不同的对象,==在比较对象时比较的是内存地址,两个是不同的空间,放的值相同
System.out.println("one==two:"+(one==two));//one==two:false
Integer three=100;//自动装箱,-> int three=100;
System.out.println("three==100:"+(three==100));//自动拆箱 true
Integer four=100;
/*实际执行的是 Integer four=Integer.valueOf(100);
* Java为了提高拆装箱效率,在执行过程中提供了一个缓存区(对象池)
* 如果传入的参数是,-128<参数<127会直接去缓存查找数据,如果没有就隐式调用new方法产生
*/
System.out.println("three==four:"+(three==four));//true
Integer five=200;
Integer six=200;
//注:这里为200,超出了缓存区范围,所以都需要构建
System.out.println("five==six:"+(five==six)); //false
}
}
注:Java中除了float和double的其他基本数据类型,都有常量池