版权声明:原创内容是本人学习总结,仅限学习使用,禁止用于其他用途。如有错误和不足,欢迎评论指正补充。 https://blog.csdn.net/qian_qian_123/article/details/82354056
1. 基本数据类型包装类
Java是一种纯面向对象语言,但是java中有8种基本数据类型,破坏了java为纯面向对象的特征。为了承诺在java中一切皆对象,java又给每种基本数据类型分别匹配了一个类,这个类我们称之为包装类。
注意:每个基本数据类型都有一个与之匹配的包装类。
1.1 八大基本数据类型的包装类
注意:int的包装类的写法为Integer、char的包装类的写法是:Character
其余基本数据类型的包装类均是基本类型的首字母大写。
1.2 包装类的层次结构
1.3 包装类中的常用方法
装箱:把基本数据类型包装为对应的包装类对象
1、 Integer i1 = new Integer(10); // 利用构造方法
2、 Integer i2 = Integer.valueOf(10); //利用包装类中的静态方法
拆箱:把包装类对象转换为对应的基本数据类型。
1、int i3= i1.intValue(); //返回包装类对象i1对应的基本数据
public class NumberWrap {
public static void main(String[] args) {
String str = "123";
// ------------- String转换成Integer
Integer integer1 = new Integer(str); // 方式一
Integer integer2 = Integer.valueOf(str); // 方式二
// ------------- String转换成int
int i2 = Integer.parseInt(str);
// ------------- Ingeter转换成String
String str2 = integer1.toString();
// ------------- 把integer转换成int
int i = integer1.intValue();
// ------------- 把int转换成Integer
Integer integer3 = new Integer(i);
// Integer integer2 = Integer.valueOf(i);
// ------------- 把int转换成String
String str3 = String.valueOf(i2); // 方式一
String str4 = i2 + ""; // 方式二
}
}
其他方法比如:
System.out.println(Integer.toBinaryString(5));//00000101
System.out.println(Integer.toHexString(15));//f
System.out.println(Integer.toOctalString(9));//11
char c = 'a';
//判断是否是一个数字
System.out.println(Character.isDigit(c));//false
1.4 自动装箱和自动拆箱
前面的装箱和拆箱操作,相对较麻烦。自jdk1.5开始,java增加的对基本数据类型的自动装箱和自动拆箱操作。
java编译器在编译时期会根据源代码的语法来决定是否进行装箱或拆箱。
1、 自动装箱:可以直接把一个基本数据类型赋值给包装类
例如: Double d = 3.3; //自动装箱操作
2、 自动拆箱:可以直接把一个包装类对象,赋值给基本类型
例如:int a = new Integer(3); //自动拆箱。
自动装箱和自动拆箱,简化了对包装类的操作。