java基本数据类型与封装类
基本数据类型:boolean、byte、short、int、long、char、float、double
对应封装类:Boolean、Byte、Short、Integer、Long、Character、Float、Double
1、已经有了基本数据类型为什么还要有封装类呢?
(1)某些时候,数据需要以对象形式出现。
如:向List中添加数据只能是对象形式;高版本JDK提供自动封包方法,如list.add(1)即可将1封包后添加到list中
(2)某些时候,使用封装类可以更方便的操作数据。
如:Integer类的valueOf()方法,Integer变量的intValue()、shortValue()、longValue()、toString()方法
2、封装类使用方法
(1)直接用封装类相关方法
String s="123";
Integer i=Integer.valueOf(a); //WrapperName.valueOf(String s),返回类型为Wrapper(Integer/Double)
int ii=5;
s=Integer.toString(ii); //WrapperName.toString(int i/double d),返回类型为String
(2)使用封装类变量相关方法
int ii=5;
Integer i=new Integer(ii);
long ll=i.longValue(); //varName.intValue/shortValue/longValue(),返回类型为int/short/long
String s=i.toString(); //varName.toString(),返回类型为String
封装类变量→基本数据类型变量:wrapperVarName.intValue()/doubleValue()/..
基本数据类型变量→封装类变量:new WrapperName(int/douible/... i)
4、两者的本质区别
(1)基本数据类型按值传递,封装类按引用传递
(2)基本数据类型在堆栈中创建;封装类是对象类,对象在堆中创建,对象的引用在堆栈中创建