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

基本数据类型和包装类的对应关系:

基本数据类型包装类
byte

Byte

shortShort
intInteger
longLong

char

Character
floatFloat

double

Double
booleanBoolean

 

基本数据类型与字符串之间的转换如下:

基本数据类型转换为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讲义

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值