java string与int转换_Java中的int与String互相转换方式

一、String转int有两种方式

(1)Integer.parseInt(str)

(2)Integer.valueOf(str).intValue()

代码如下·:

String str= "123";

int n=0;

//(1)Integer.parseInt(str)

for(int i=0; i<100000; i++){

n = Integer.parseInt(str);

}

System.out.println("Integer.parseInt(str) : " + n);

System.out.println();

//(2)Integer.valueOf(str).intValue()

n=0;

for(int i=0; i<100000; i++){

n = Integer.valueOf(str).intValue();

}

System.out.println("Integer.parseInt(str) : " + n);1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

运行结果

e17afe1ce16da091c1f8b0c37264b304.png

二、int转String有三种方式

(1)num + “”

(2)String.valueOf(num)

(3)Integer.toString(num)

代码如下:

int num=10;

for(int i=0;i<5;i++) {

String str=num+"";

num++;

System.out.println("str1:"+str);

}

System.out.println();

num=10;

for(int i=0;i<5;i++) {

String str2 = String.valueOf(num);

num++;

System.out.println("str2:"+str2);

}

System.out.println();

num=10;

for(int i=0;i<5;i++) {

String str3 = Integer.toString(num);

num++;

System.out.println("str3:"+str3);

}1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

89408d9bb19ffdd69826291369755f14.png

使用第一种方法相对第二第三种耗时比较大

String.valueOf():采用String.valueOf(object)的基础是Object#toString(),但这里不用担心object是否为null这一问题,JDK中String#valueOf(object)源码:

public static String valueOf(Object obj){return (obj==null)?"null":obj.toString();}1

所以使用该方法不必担心object为null的情况,但同时注意当object为null时该方法返回"null",而非null!!!

**Integer.toString();**采用Integer.toString()的基础仍是Object#toString(),因为java.lang.Object类中已有public方法toString(),所以对任何严格意义上的Java对象都可以调用此方法,但使用时需要注意,必须保证object不是null值,否则将会抛出NullPointerException异常!!!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值