Java基本数据类型与包装类、字符串之间的转换

基本数据类型和包装类的转换:
1、装箱:基本数据类型→对应包装类,可分为手动装箱和自动装箱。
2、拆箱:包装类→对应基本数据类型,可分为手动拆箱和自动拆箱。

例子:
手动装箱:Integer iObj=new Integer(1);
自动装箱:Integer iObj=1;
手动拆箱:int i=(new Integer(1)).intValue();
自动拆箱:int i=new Integer(1);

基本数据类型和字符串的转换:
1、基本数据类型→字符串:
Ⅰ 、使用对应包装类的toString()方法:(new Integer(1)).toString(); //结果为"1"
Ⅱ、使用String类的valueOf()方法:String.valueOf(1); //结果为"1"
Ⅲ、使用空字符串""加上基本数据类型:""+1; //结果为"1"
2、字符串→基本数据类型:
Ⅰ 、使用要转换为的基本数据类型的包装类的parseXxx()方法:Integer.parseInt("1"); //结果为1
Ⅱ、使用要转换为的基本数据类型的包装类的valueOf()方法:Integer.valueOf("1"); //结果为1,实际是转为的Integer类型,但会自动拆箱


作者:小明同学爱思考
链接:http://www.imooc.com/article/6541
来源:慕课网

原文地址:https://www.cnblogs.com/banxian-yi/p/10579338.html