@[TOC](JAVA String转int(Integer.parseInt()和Integer.valueOf()))
前言
不想看分析直接跳到最后看结论。
一、常用函数
常用函数有两个:Integer.parseInt()和Integer.valueOf()。
1. parseInt
//parseInt返回int
public static int parseInt(String s) throws NumberFormatException {
return parseInt(s,10);
}
2. valueOf
//返回int的封装类Integer
public static Integer valueOf(String s) throws NumberFormatException {
return Integer.valueOf(parseInt(s, 10));
}
parseInt与valueOf的相同点与区别
- Integer.parseInt(String s)和Integer.valueOf(String s)都调用了Integer.parseInt(String s, int radix)函数来处理String到int的转换
- Integer.parseInt()返回int,Integer.valueOf()返回int的封装类Integer
调用关系图:
二、实例
实例一
public class Main {
public static void main(String[] args){
String a = "123";
int x = Integer.parseInt(a);
int y = Integer.valueOf(a);//编译器提示'Integer.valueOf(a)' 内的装箱冗余
System.out.println(x);
System.out.println(y);
}
}
- int y = Integer.valueOf(a); 编译器会提示’Integer.valueOf(a)’ 内的装箱冗余,因为这里valueOf对int进行封装变成Integer类型,然后y是int型又需要对这个Integer类型进行拆包,使得封装这一步变得多余了,直接使用parseInt比较好
运行结果:
实例二
public class Main {
public static void main(String[] args){
String a = "123.0";
int x = 0;
int y = 0;
//parseInt
try{
x = Integer.parseInt(a);
System.out.println(x);
}catch(NumberFormatException e){
System.out.println("parseInt throw NumberFormatException");
}
//valueOf
try{
y = Integer.parseInt(a);
System.out.println(y);
}catch(NumberFormatException e){
System.out.println("valueOf throw NumberFormatException");
}
}
}
- 不管是parseInt还是valueOf,遇到非纯整数的数字字符串都是会抛出NumberFormatException异常的
运行结果:
结论
- 两个String→int的函数:
- Integer.parseInt(String s)
- Integer.valueOf(String s)
- 遇到非纯整数字符串都会抛出NumberFormatException
- valueOf实际调用parseInt,然后多了一步Integer的封装
- 对int型的变量赋值建议使用parseInt,对Integer变量赋值建议使用valueOf