封装类
所有的基本类型,都有对应的类类型
比如int对应的类是Integer
这种类就叫做封装类
package digit;
public class TestNumber {
public static void main(String[] args) {
int i = 5;
//把一个基本类型的变量,转换为Integer对象
Integer it = new Integer(i);
//把一个Integer对象,转换为一个基本类型的int
int i2 = it.intValue();
}
}
Number类
public class TestNumber {
public static String getType(Object o) {
return o.getClass().toString();
}
public static void main(String args[]) {
int a = 5;
Integer it = new Integer(a);
System.out.println(it instanceof Number);
}
}
基本类型转封装类
public class TestNumber {
public static String getType(Object o) {
return o.getClass().toString();
}
public static void main(String args[]) {
int a = 100;
Integer it = new Integer(a);
}
}
封装类转基本类型
package digit;
public class TestNumber {
public static void main(String[] args) {
int i = 5;
//基本类型转换成封装类型
Integer it = new Integer(i);
//封装类型转换成基本类型
int i2 = it.intValue();
}
}
自动装箱
不需要调用构造方法,通过=符号自动把 基本类型 转换为 类类型 就叫装箱
package digit;
public class TestNumber {
public static void main(String[] args) {
int i = 5;
//基本类型转换成封装类型
Integer it = new Integer(i);
//自动转换就叫装箱
Integer it2 = i;
}
}
自动拆箱
package digit;
public class TestNumber {
public static void main(String[] args) {
int i = 5;
Integer it = new Integer(i);
//封装类型转换成基本类型
int i2 = it.intValue();
//自动转换就叫拆箱
int i3 = it;
}
}
int的最大值,最小值
int的最大值可以通过其对应的封装类Integer.MAX_VALUE获取
public class TestNumber {
public static String getType(Object o) {
return o.getClass().toString();
}
public static void main(String args[]) {
System.out.println(Integer.MAX_VALUE);
System.out.println(Integer.MIN_VALUE);
}
}
练习-装箱拆箱
public class TestNumber {
public static String getType(Object o) {
return o.getClass().toString();
}
public static void main(String args[]) {
int a = 100;
Integer b = a;//拆箱操作
float c = 100;
Float d = c;//拆箱操作
int q = 200;
Float q1 = new Float(q);
int q2 = q1.intValue(); //封装类型转换成基本类型
int q3 = q2; //自动拆箱操作
}
}