基本数据类型、包装类、String之间的转换

xiaoxiao2021-02-27  432

package 包装类; /** *8种基本数据类型对应一个类,此类即为包装类 * 基本数据类型、包装类、String之间的转换 * 1.基本数据类型转成包装类(装箱): * ->通过构造器 :Integer i = new Integer(11) * ->通过字符串参数:Float f = new Float("12.1f") * ->自动装箱 * 2.基本数据类型转换成String类 * ->String类的:valueof(2.1f) * ->2.1+" " * 3.包装类转换成基本数据类型(拆箱): * ->调用包装类的方法:xxxValue() * ->自动拆箱 * 4.包装类转换成String类 * ->包装类对象的toString方法 * ->调用包装类的toString(形参) * 5.String类转换成基本数据类型 * ->调用相应包装类:parseXxx(String)静态方法 * ->通过包装类的构造器:Integer i = new Integer(11) * 6.String类转换成包装类 * ->通过字符串参数:Float f = new Float("12.1f") * */ import org.junit.Test; public class TestWrapper { //基本数据类型和包装类之间的转换 @Test//单元测试 public void test1(){ int i = 10;//基本数据类型 float f = 10.1f; Integer i1 = new Integer(i);//包装类 Float f1 = new Float(f); String str = "123";//字符串 //1.基本数据类型转成包装类(装箱): Float f2 = new Float(1.0);//参数可以是包装类对应的基本数据类型 Float f3 = new Float("1.0");//也可以是字符串类型,但其实体(其值)必须是对应的基本数据类型 System.out.println("基本数据类型转成包装类:"+f2); System.out.println("基本数据类型转成包装类:"+f3); //2.基本数据类型转换成String类 String str1 = String.valueOf(f); String str2 = f+" "; System.out.println("基本数据类型转换成String:"+str1); System.out.println("基本数据类型转换成String:"+str2); //3.包装类转换成基本数据类型(拆箱): int i2 = i1.intValue(); int i3 = i1;//自动拆箱 System.out.println("包装类转换成基本数据类型"+i2); System.out.println("包装类转换成基本数据类型"+i3); //4.包装类转换成String类 String str3 = f1.toString(); String str4 = Float.toString(f1); System.out.println("包装类转换成String类"+str3); System.out.println("包装类转换成String类"+str4); //5.String类转换成基本数据类型 int i4 = Integer.parseInt(str); int i5 = Integer.valueOf(str); System.out.println("String类转换成基本数据类型"+i4); System.out.println("String类转换成基本数据类型"+i5); //6.String类转换成包装类 Integer i6 = new Integer(str); System.out.println("String类转换成包装类"+i6); } }
转载请注明原文地址: https://www.6miu.com/read-412.html

最新回复(0)