Java 中 String 转 Integer 的方法与底层原理详解

✨ 一、常见的转换方式

Java 中将 String 转为 Integer(或 int)常用三种方式:

java 复制代码
String str = "123";

// 方法1:使用 Integer.parseInt()
int num1 = Integer.parseInt(str);

// 方法2:使用 Integer.valueOf()
Integer num2 = Integer.valueOf(str);

// 方法3:使用 new Integer()(不推荐)
Integer num3 = new Integer(str); // 已过时,不推荐

🔍 二、三种方式的区别

方法 返回类型 是否装箱 是否推荐 原理说明
parseInt int ❌ 无自动装箱 ✅ 推荐 内部直接解析字符串成 int
valueOf Integer ✅ 自动装箱 ✅ 推荐 实际调用了 parseInt() 并进行装箱
new Integer(str) Integer ✅ 装箱 ❌ 不推荐 每次 new 一个对象,不走缓存机制,性能差

🧠 三、底层原理解析(重点)

我们重点来看看 Integer.parseInt(String) 的源码和原理:

🔧 源码分析(简化)

java 复制代码
public static int parseInt(String s) throws NumberFormatException {
    if (s == null) {
        throw new NumberFormatException("null");
    }

    int result = 0;
    boolean negative = false;
    int i = 0, len = s.length();

    // 处理负号
    char firstChar = s.charAt(0);
    if (firstChar == '-') {
        negative = true;
        i++;
    }

    while (i < len) {
        int digit = s.charAt(i++) - '0';  // 将字符 '1' 转为数字 1
        if (digit < 0 || digit > 9) throw new NumberFormatException();
        result = result * 10 + digit;
    }

    return negative ? -result : result;
}

📌 说明:

  • s.charAt(i) - '0':通过字符 ASCII 值转换成整数(比如 '3' 的 ASCII 是 51,'0' 是 48,51-48=3)
  • 字符逐个读取并计算:result = result * 10 + digit
  • 支持负数
  • 抛出异常:如果不是合法数字字符,就抛出 NumberFormatException

图片示例:对 "-1314" 进行 String 转换至 Integer


💡 四、装箱与缓存机制(valueOf 的核心区别)

java 复制代码
Integer.valueOf("123");

这个方法会先执行:

java 复制代码
int i = Integer.parseInt("123");

然后执行装箱:

java 复制代码
return Integer.valueOf(i);

🧠 Integer 缓存池机制:

Java 对于 [-128, 127] 之间的整数做了缓存,所以多次 valueOf(127) 实际上返回的是同一个对象。

java 复制代码
Integer a = Integer.valueOf(127);
Integer b = Integer.valueOf(127);
System.out.println(a == b); // true

Integer c = Integer.valueOf(128);
Integer d = Integer.valueOf(128);
System.out.println(c == d); // false

✅ 面试陷阱点总结

考点 解答
parseIntvalueOf 的区别? 一个返回 int,一个返回 Integer,后者有装箱过程
哪个方法更推荐? valueOf 推荐用于对象封装,parseInt 更轻量用于原始类型
Integer.valueOf() 有缓存机制吗? ✅ 有,范围是 [-128, 127]
为什么 new Integer() 不推荐? 每次都会创建新对象,浪费内存,不走缓存池

📘 延伸知识

  • 反过来 Integer → String 怎么转?

    java 复制代码
    String s = String.valueOf(123);
    String s2 = Integer.toString(123);

🧩 Mermaid 图解:String 转 Integer 的常见方式及原理

String str = S\ Integer.parseInt(str) 返回 int 类型 内部逐字符计算
result = result * 10 + digit Integer.valueOf(str) 先调用 parseInt(str) 然后 Integer.valueOf(int) 触发装箱 & 缓存机制 返回 Integer 对象 new Integer(str) 调用构造函数 不使用缓存,每次都新建对象


📌 图解说明:

  • parseInt() 返回基本类型 int,适合纯粹数值计算。
  • valueOf() 是包装类推荐方式,支持缓存池([-128, 127])。
  • new Integer() 会创建新的对象,已被标记为不推荐(已废弃)。
相关推荐
越来越无动于衷13 分钟前
手写tomcat:基本功能实现(3)
java·tomcat
Uranus^16 分钟前
使用Spring Boot和Spring Security构建安全的RESTful API
java·spring boot·spring security·jwt·restful api
qq_5432485217 分钟前
Tomcat的调优
java·tomcat
Mcworld85722 分钟前
String的一些固定程序函数
java
越来越无动于衷23 分钟前
手写tomcat:基本功能实现(4)
java·tomcat
编程乐学(Arfan开发工程师)23 分钟前
06、基础入门-SpringBoot-依赖管理特性
android·spring boot·后端
编程乐学(Arfan开发工程师)24 分钟前
05、基础入门-SpringBoot-HelloWorld
java·spring boot·后端
小智学长 | 嵌入式25 分钟前
进阶-数据结构部分:2、常用排序算法
java·数据结构·算法
保利九里1 小时前
java中的包机制
java·开发语言
努力学习的明1 小时前
Spring MVC 中请求处理流程及核心组件解析
java·spring·mvc