基本数据类型和包装类的对应关系:
基本数据类型 | 包装类 |
byte | Byte |
short | Short |
int | Integer |
long | Long |
char | Character |
float | Float |
double | Double |
boolean | Boolean |
基本数据类型与字符串之间的转换如下:
基本数据类型转换为String对象:通过String.valueOf(primitive)
String对象转换为基本数据类型:通过WrapperClass.parseXxx(String)
示例代码:
/**
* 说明:基本数据类型与字符串之间的转换
* 方法1:基本数据类型变成Sting对象:通过String.valueOf(primitive)转换
* 方法2:String对象变成基本数据类型:通过WrapperClass。parseXxx()转换,Character包装类无此方法
* @author LiuYP_1024
*
*/
public class PrimitiveAndString {
public static void main(String[] args) {
String num="123";
String floatStr="4.56";
//将字符串转化为byte
byte byte1=Byte.parseByte(num);
System.out.println(byte1);
//将字符串转化为short和long
short short1=Short.parseShort(num);
System.out.println(short1);
long long1=Long.parseLong(num);
//把字符串转化为int
int int1=Integer.parseInt(num);
int int2=new Integer(num);
System.out.println(int1);
System.out.println(int2);
//把字符串转化为float
float float1=Float.parseFloat(floatStr);
float float2=new Float(floatStr);
System.out.println(float1);
System.out.println(float2);
//将float和double转换为String
String str1=String.valueOf(2.234f);
String str2=String.valueOf(3.344);
System.out.println(str1);
System.out.println(str2);
//将boolean转换为String
String str3=String.valueOf(true);
System.out.println(str3);
}
}
此外,将基本数据类型转换为字符串,有另一种更简便的方法:将基本数据类型变量直接与“”进行连接运算,如下
String intStr=5+"";
内容整理来源于:疯狂Java讲义