Java学习——包装类
摘要:本文主要介绍了Java中常用的包装类和基本类型之间的转换,包装类或基本类型和String之间的转换。
部分内容来自以下博客:
https://www.cnblogs.com/future-liu1121/p/6556153.html
为什么要使用包装类
Java中的基本类型功能简单,不具备对象的特性,为了使基本类型具备对象的特性,所以出现了包装类,就可以像操作对象一样操作基本类型数据。
装箱和拆箱
装箱
装箱就是根据数据创建对应的包装对象。
JDK1.5之后提供了自动装箱的机制。
1 Integer a = new Integer(10); 2 Integer b = 10;// 自动装箱
拆箱
拆箱就是将包装类型转换为基本数据类型。
JDK1.5之后提供了自动拆箱的机制。
1 int c = a.intValue(); 2 int d = b;// 自动拆箱
包装类或基本类型和字符串的转换
包装类或基本类型转字符串
调用包装类的toString()方法。
调用String类的valueOf()方法。
基本类型可以直接加空字符串。
字符串转包装类或基本类型
调用包装类的valueOf()方法。
调用包装类的parseXxx()方法。