1.基础数据类型转包装类
基础数据类型的转换使用的是包装类的静态方法valueOf(a),a为包装类对应的基础类型,使用反射包装类对象.getClass().getName()获取包装类class名称。
int i=11;
Integer integer1 = Integer.valueOf(i);
System.out.println(integer1.getClass().getName());
Integer integer2 = new Integer(i);
System.out.println(integer2.getClass().getName());
boolean bo=true;
Boolean boolean1 = Boolean.valueOf(bo);
Boolean boolean2 = new Boolean(bo);
byte b=11;
Byte byte1 = Byte.valueOf(b);
Byte byte2 = new Byte(b);
char c='a';
Character character1 = Character.valueOf(c);
Character character2 = new Character(c);
short s=11;
Short short1 = Short.valueOf(s);
Short short2 = new Short(s);
long l=11;
Long long1= Long.valueOf(11);
Long long2 = new Long(11);
float f=3.14f;
Float float1 = Float.valueOf(f);
Float float2 = new Float(f);
double d=3.14;
Double double1 = Double.valueOf(d);
Double double2 = new Double(d);
2.包装类转基础数据类型
以包装类Integer为例,integer1可以转化为int或是byte、short等数字类型的基础数据类型。其它Byte、Short等包装类对象也可以使用相应的Value方法转化为任意数字类型的基础数据类型。
int intValue = integer1.intValue();
byte byteValue = integer1.byteValue();
short shortValue = integer1.shortValue();
float floatValue = integer1.floatValue();
double doubleValue= integer1.doubleValue();
System.out.println(intValue+" "+byteValue+" "+shortValue+" "+floatValue+" "+doubleValue);
3.String转基础数据类型
java中,String是一种特殊的引用类型,它用于表示字符串,提供了一系列操作字符串的方法。String类型可以转换成基础数据类型,但是要符合规定,例如"abc"的字符串不可以转数字类型,数字类型不可以转boolean类型。
String s1="123";
int parseInt = Integer.parseInt(s1);
byte parseByte = Byte.parseByte(s1);
short parseShort = Short.parseShort(s1);
float parseFloat = Float.parseFloat(s1);
double parseDouble = Double.parseDouble(s1);
System.out.println(parseInt+" "+parseByte+" "+parseShort+" "+parseFloat+" "+parseDouble);
下面是关于String转char和boolean的
String s2="abc";
char[] chars = s2.toCharArray();
for(char cc:chars){
System.out.println(cc);
}
String s3="true";
boolean b1 = Boolean.parseBoolean(s3);
System.out.println(b1);
4.包装类或基础数据类型转String
//包装类转string
String valueOf1 = String.valueOf(integer1);
String valueOf2 = String.valueOf(double1);
String valueOf3 = String.valueOf(boolean1);
String valueOf4 = String.valueOf(character1);
//基础数据类型转string
String valueOf5 = String.valueOf(i);
String valueOf6 = String.valueOf(b);
System.out.println(valueOf1+" "+valueOf2+" "+valueOf3+" "+valueOf4+" "+valueOf5+" "+valueOf6);
包装类可以直接点toString()方法转成String类型。