在Java中,很多类的方法都需要接收引用类型的对象,此时就无法将一个基本数据类型的值传入。为了解决这样的问题,JDK中提供了一个系列的包装类,通过这些包装类可以将基本数据类型的值包装为引用数据类型的对象。在Java中,每种基本类型都有对应的包装类。
基本数据类型 | 对应的包装类 |
---|---|
byte | Byte |
char | Character |
int | Integer |
short | Short |
long | Long |
float | Float |
double | Double |
boolean | Boolean |
包装类和基本数据类型在进行转换时,引入了装箱和拆箱的概念,其中装箱时指将基本数据类型的值转为引用数据类型;反之,拆箱是指将引用数据类型的对象转为基本数据类型。
1.包装类都重写了Object类中的toString()方法,以字符串的形式返回被包装的基本数据类型的值。
2. 除了Character外,包装类都有valueOf(String s)方法,可以根据String类型的参数创建类对象,但参数字符串s不能为null,而且字符串必须是可以解析为相应基本类型的数据,否则虽然编译通过,但运行时会报错。
Integer i=Integer.valueOf("123");//合法
Integer i=Integer.valueOf("123a");//不合法
3.除了Character外,包装类都有parseXXX(String s)的静态方法,将字符串转换为对应的基本类型的数据。参数s不能为null,而且同样必须是可以解析为相应基本类型的数据,否则虽然编译通过,但是运行时会报错。
int i=Integer.parseInt("123");//合法
Integer in=Integer.parseInt("eaglezsx");//不合法
Integer类
将基本数据类型封装成对象的好处在于可以在对象中定义更多的方法来操作数据。
比如,将一个十进制数转换成二进制。
public static void main(String[] args) {
String s=Integer.toBinaryString(23);
System.out.println(s);
}
运行结果为
10111
构造方法
- Integer(int value)
- Integer(String s)
Integer i1=new Integer(100);
Integer i2=new Integer("100");//只能是数字字符串
常量
System.out.println(Integer.MAX_VALUE);//2147483647
System.out.println(Integer.MIN_VALUE);//-2147483648
类型转换
int—>String
- 和“”进行拼接
- static String valueOf(int i)
- int先转换成Integer,再通过Integer中的toString方法
- 用Integer类中的static String toString(int i)方法
int i=100;
String s1=i+"";
String s2=String.valueOf(i);
Integer i2=new Integer(i);
String s3=i2.toString();
String s4=Integer.toString(i);
String—>int
- 将String转换成Integer,再调用intValue方法
- 直接调用Integer中的静态方法parseInt
String s="100";
Integer i=new Integer(s);
int i2=i.intValue();
int i3=Integer.parseInt(s);
JDK1.5新特性—自动拆箱和装箱
在JDK1.5版本之前,数学运算表达式中的操作数必须是基本数据类型的,并且运行结果也是基本数据类型,包装类和基本类型是不允许进行混合数学运算的,如果想运算,必须要通过拆箱将包装类对象转为基本数据类型的值才行。
在JDK1.5的版本中提供了自动拆箱和装箱技术,也就是可以自动进行基本数据类型和包装类对象之间的转换。
int x=100;
Integer i1=new Integer(x);//将基本数据类型包装成对象,装箱
int y=i1.intValue(); //将对象转换为基本数据类型,拆箱
//----------------------------------------
Integer i2=100;//自动装箱,把基本数据类型转换成对象
int z=i2+100; //自动拆箱,把对象转换为基本数据类型