https://blog.csdn.net/weixin_43972361/article/details/89575721
一、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
运行结果
 
二、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

 使用第一种方法相对第二第三种耗时比较大
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异常!!!
 
                    
                 

 
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号