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() 会创建新的对象,已被标记为不推荐(已废弃)。
相关推荐
西瓜本瓜@1 小时前
在Android中如何使用Protobuf上传协议
android·java·开发语言·git·学习·android-studio
言之。1 小时前
别学了,打会王者吧
java·python·mysql·容器·spark·php·html5
机智的人猿泰山1 小时前
java kafka
java·开发语言·kafka
Algorithm15762 小时前
谈谈接口和抽象类有什么区别?
java·开发语言
yu4106212 小时前
Rust 语言使用场景分析
开发语言·后端·rust
细心的莽夫2 小时前
SpringCloud 微服务复习笔记
java·spring boot·笔记·后端·spring·spring cloud·微服务
jack_xu4 小时前
高频面试题:如何保证数据库和es数据一致性
后端·mysql·elasticsearch
264玫瑰资源库4 小时前
问道数码兽 怀旧剧情回合手游源码搭建教程(反查重优化版)
java·开发语言·前端·游戏
东阳马生架构4 小时前
Nacos简介—2.Nacos的原理简介
java