String 和 Integer、int 之间的转换

1. String <===> Integer
1.1. String 转 Integer

注:当我们要把 String 转化为 Integer 时,一定要对 String 进行非空判断,否则很可能报空指针异常。

String str = "12345";
Integer i = null;
if(str != null){
     i = Integer.valueOf(str);
}
1.2. Integer 转 String
//方法一:Integer 类的静态方法 toString()
Integer a = 2;
String str = Integer.toString(a)
 
//方法二:Integer 类的成员方法 toString()
Integer a = 2;
String str = a.toString();
 
//方法三:String 类的静态方法 valueOf()
Integer a = 2;
String str = String.valueOf(a);

注意事项:
依据源码规则,使用这 3 种方法时,需注意以下几点:
1、通过 toString() 方法,可以把整数(包括0)转化为字符串,但是 Integer 如果是 null 的话,就会报空指针异常。
2、String.valueOf(Object obj) 可以把整型(包括0)转化为字符串,但是 Integer 如果是 null 的话,会转化为“null”。

引申:
当 Integer 是 null 的情况下,我们也希望 String 是 null,上面的方法都没法做到。可以自己写一个方法:

 public static String toString(Object obj) {
        return (obj == null) ? null : obj.toString();
    }
2. String <===> int
2.1. int 转 String

int 类型是值类型,没有 toString 方法,要将 int 类型转换成 String 类型,可以用 int 的对应类 Integer 中的 toString 方法来将 int 类型转换成 String 类型。

int num = 45;
String str = Integer.toString(num);
2.2. String 转 int

通过用创建一个 Integer 对象的方式来将 String 类型转换成int类型

String str = "55";
int num = new Integer(str);

注意事项:
将 String 类型转换成 int 类型时,需要注意 String 类型存储的字符串必须是整型格式的,不然转换的过程会报错。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Gorden_Zhu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值