基本类型包装类的基本使用:实现字符串与基本数据之间转换
基本类型包装类作用:实现字符串与基本数据之间转换
8种基本类型对应的包装类如下:
其中需要注意int对应的是Integer,char对应的Character,其他6个都是基本类型首字母大写即可。
字符串转基本类型
String a="12345";
int a1=Integer.parseInt(a);
int math=a1+1;
System.out.println(math);//字符串转基本类型
结果:12346
基本类型转字符串
int b=4567;
String b1=String.valueOf(b);
String b2=Integer.toString(b);
System.out.println((b1+8)+","+(b2+9));//基本类型转字符串
结果:45678,45679
基本数值转换包装对象
1.使用构造函数实现
int c=789;
String d="666";
Integer c1=new Integer(c);
Integer d1=new Integer(d);//使用构造函数实现--基本数值转换包装对象
2.使用包装类valueof方法实现
Integer c2=Integer.valueOf(c);
Integer d2=Integer.valueOf(d);//使用包装类valueof方法实现--基本数值转换包装对象
int d3=d2.intValue();
System.out.println((d1+1)+","+(d2+2)+","+(d3-1));
结果:667,668,665
自动装箱自动拆箱
int e=778;
Integer x=e;//相当于Integer.valueOf(e);----自动装箱过程
x=x+1;//相当于x转换为基本数值(自动拆箱过程)x.intValue()+1;加法运算完后再自动装箱,把基本数值转换成为对象
注意:
Integer f=100;
Integer g=100;
System.out.println((f==g)+","+(f.equals(g)));//数值<128,为了节约内存空间,指向的是同一个对象。
Integer f1=200;
Integer g1=200;
System.out.println((f1==g1)+","+(f1.equals(g1)));//数值>128分别指向自己创建的对象,
Integer f2=new Integer(100);
Integer g2=new Integer(100);
System.out.println((f2==g2)+","+(f2.equals(g2)));//数值虽然小于128但是使用的是new Integer()直接创建的新的对象
结果: true,true
false,true
false,true