包装类
针对八种基本数据类型,相应的引用类型-包装类
从byte到double的包装类的类都是Number的子类
Boolean和Character直接父类就是Object
Byte和Integer等是继承Number然后Number继承Object
包装类和基本数据类型的转换
以int和Integer
装箱:基本类型到包装类型(int-》Integer)
拆箱:包装类型到基本类型(Integer-》int)
自动装箱和手动装箱
package com.hansp.wrapper;
public class Integer01 {
public static void main(String[] args) {
//演示装箱和拆箱
//jdk5以前手动装箱和拆箱
int n1=100;
//手动装箱
Integer integer01 = new Integer(n1);
//或者
Integer integer = Integer.valueOf(n1);
//手动拆箱
int i=integer.intValue();
//手动装箱和拆箱需要调用对应方法
//jdk5以后就可以自动装箱和自动拆箱了
//自动装箱
int n2=200;
Integer integer2=n2;//底层仍然是Integer.valueOf(n2)
//自动拆箱
int n3 =integer2;//底层任然是用intValue()方法
}
}
易错
在定义时,一定要看清是对象还是基本数据类型
1.
double d=100d;
Double d2=100d;
//两种写法都对,但是d是基本数据类型,d2是自动装箱后的Double对象
其他的同理
2.
输出1.0
因为三元运算符要看做一个整体,要像最高位看齐转换
包装类和String类型相互转换
以Integer为例
包装类转String
Integer i=10;
//方式1
String str1=i+"";
//方式2
String str2=i.toString();
//方式3
String str3=String.valueOf(i);
String转包装类
String str4="12345";
//法1
Integer i2=Integer.parseInt(str4);//parseInt返回int类型但是自动装箱变为Integer
//法2
Integer i3=new Integer(str4);//构造器
包装类的常用方法
最小值和最大值是对应的基本数据类型能存储的最小值和最大值(与字节有关)
Integer创建机制
false
true
false
解析:
第一个判断i和j是不是同一个对象,显然不是,因为两个对象但是new出来的
第二个底层是用的Integer.valueOf(1)
看源码
与范围有关,不在范围内才会新建对象
范围是从-128到127
所以不会新建Integer对象
返回true
第三个和第二个同理,但是128超出范围,所以最后返回true
本质是本来-128到127是本来就给你创建好了,所以调用的是一个,但是不在这个范围内的都是返回一个新建的对象!!!