1. 返回类型:
Integer.valueOf(String) 返回一个 Integer 对象。
Integer.parseInt(String) 返回一个原始的 int 值。
public class TestDemo {
public static void main(String[] args) {
String str="123";
Integer intValue = Integer.valueOf(str); // 返回 Integer 对象
int intValue1 = Integer.valueOf(str);//拆箱
int intValuePrimitive = Integer.parseInt(str); // 返回 int 值
System.out.println(intValue);
System.out.println(intValue1);
System.out.println(intValuePrimitive);
}
}
Integer.valueOf(str)
返回的是一个Integer
对象,因此如果需要将其赋值给一个基本数据类型的变量,会发生自动拆箱。
运行结果:
2. 异常处理:
- Integer.valueOf(str) 在遇到无法转换为整数的字符串时会抛出 NumberFormatException 异常。
- Integer.parseInt(str) 也会在遇到无法转换为整数的字符串时抛NumberFormatException 异常。
3.性能:
Integer.valueOf(str) 会创建一个新的 Integer 对象
Integer.parseInt(str) 不会创建对象,直接返回一个基本数据类型的值。因此,如果只需要使用整数的值而不需要 Integer 对象的其他特性,parseInt 的性能可能更好一些。
4.总结:
通常情况下,如果只需要使用整数的值而不需要 Integer 对象,建议使用 Integer.parseInt(str) 方法。如果需要将整数作为对象进行操作,则可以使用 Integer.valueOf(str)。