- 基本类型包装类的概述
将基本数据类型封装成对象的好处在于可以在对象中定义更多的功能方法操作该数据。
常用的操作之一:用于基本数据类型与字符串之间的转换。 - 基本数据类型与包装类的对应关系
byte → Byte
short → Short
int → Integer
long → Long
float → Float
double → Double
char → Character
boolean→ Boolean
- 将字符串转成基本类型
parseXXX(String s);其中XXX表示基本类型,参数为可以转成基本类型的字符串,如果字符串无法转成基本类型,将会发生数字转换的问题 NumberFormatException
System.out.println(Integer.parseInt("123") + 2);
//打印结果为 125
将基本数值转成字符串有3种方式:
基本类型直接与””相连接即可;34+""
调用String的valueOf方法;String.valueOf(34) ;
调用包装类中的toString方法;Integer.toString(34)
int a=Integer.parseInt("12");
double b=Double.parseDouble("2.5");
System.out.println(b+1);
//将基本数据类型装转化字符串:
//1.基本类型+””相连接即可;34+""
int c=3;
System.out.println((c+"")+1);
//2.String类型中的valueof方法,调用String的valueOf方法;String.valueOf(34)
int d=7;
System.out.println(String.valueOf(d)+1);
System.out.println(String.valueOf(true)+1);
//3.包装类中的带参的toString(基本类型 变量)
int e=8;
System.out.println(Integer.toString(e)+1);
- 基本类型和对象转换
基本数值–>包装类
Integer i = new Integer(4);//使用构造函数函数
Integer ii = new Integer("4");//构造函数中可以传递一个数字字符串
Integer iii = Integer.valueOf(4);//使用包装类中的valueOf方法
Integer iiii = Integer.valueOf("4");//使用包装类中的valueOf方法
包装类–>基本类型
int num = i.intValue();
自动装箱拆箱
自动拆箱:对象自动直接转成基本数值
自动装箱:基本数值自动直接转成对象
Integer i = 4;//自动装箱。相当于Integer i = Integer.valueOf(4);
i = i + 5;//等号右边:将i对象转成基本数值(自动拆箱) i.intValue() + 5; 加法运算完成后,再次装箱,把基本数值转成对象。
当数值在byte范围之内时,进行自动装箱,不会新创建对象空间而是使用已有的空间,byte范围内(-128——127)。
Integer a = new Integer(3);
Integer b = new Integer(3);
System.out.println(a==b);//false
System.out.println(a.equals(b));//true
System.out.println("---------------------");
Integer x = 127;
Integer y = 127;
//在jdk1.5自动装箱时,如果数值在byte范围之内,不会新创建对象空间而是使用原来已有的空间。
System.out.println(x==y); //true
System.out.println(x.equals(y)); //true
一道例题
Integer i1 = 97;
Integer i2 = 97;
System.out.println(i1 == i2);
System.out.println(i1.equals(i2));
System.out.println("-----------");
Integer i3 = 197;
Integer i4 = 197;
System.out.println(i3 == i4);
System.out.println(i3.equals(i4));
输出
true
true
false
true