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

@Test
public void test2(){
//基本数据类型、包装类-->到String类型的转换,调用String类型的静态方法valueOf()即可
int i1 = 12;
String str = String.valueOf(i1);//"10"
String str1 = String.valueOf(true);//"true"
System.out.println(str1);

//String类型-->基本数据类型、包装类:调用包装类的parseXxx()方法即可
int i2 = Integer.parseInt(str);
System.out.println(i2);//12
boolean b = Boolean.parseBoolean(str1);
System.out.println(b);//true
}

@Test
public void test1(){
int i = 10;
float f = 12.0f;
//基本数据类型-->对应的包装类,调用包装类的构造器即可,转化方式 1
Integer i1 = new Integer(i);
System.out.println(i1);//10
//转换方式 2,构造器里面直接放int类型的数据
i1 = new Integer(66);
//转换方式 3,构造器里面直接放String类型的int数据
Integer i2 = new Integer("66");
System.out.println("i2 "+i2);
//当然这么做是错误的,会报NumberFormatException的异常
//Integer i3 = new Integer("66sdf");

//Float类型转换可以这么直接写
Float f1 = new Float(13.2f);
System.out.println(f1);//13.2
//当然也可以写成字符串的形式
Float f2 = new Float("13.2f");
System.out.println(f2);//13.2

//★对于Boolean类型来说,当形参是"true"返回true,除此以外返回false
//构造器里面可以直接写true
Boolean boo = new Boolean(true);//true
//构造器里面也可以写字符串形式的"true"
Boolean boo1 = new Boolean("true");//true
//这么写就是错误的,会返回false
Boolean boo2 = new Boolean("truesdd");//false
//当然,这么写就是错误的,会返回false
Boolean boo3 = new Boolean("falsecd");//false
//当然,这么写就是正确的,会返回false
Boolean boo4 = new Boolean("false");//false
//当然,这么写就是正确的,会返回false
Boolean boo5 = new Boolean(false);//false
System.out.println(boo5);

//包装类转换为基本数据类型的,直接调用包装类Xxx的XxxValue()的方法
int num = i1.intValue();
float fa = f1.floatValue();
boolean fage = boo.booleanValue();

//当然,jdk5.0以后,实现了自动装箱和拆箱
Integer i4 = 13;//自动装箱
Boolean boo8 = true;//自动装箱
int i5 = i4;//自动拆箱
boolean boo6 = boo8;//自动拆箱
}

转https://blog.csdn.net/XF777/article/details/72628171

猜你喜欢

转载自www.cnblogs.com/GtShare/p/9298345.html