java中所有返回string的方法均创建并返回新对象,原字符串不可变;如concat、substring、replace、touppercase等;而length、charat等返回非string类型的方法不产生新对象。

Java 中 String 类的所有实例方法,只要返回类型是 String,一律返回一个全新的 String 对象 —— 原对象从不被修改。这是由 String 的不可变性(immutability)决定的,不是某些方法“选择”返回新对象,而是设计上根本无法修改自身。
所有返回 String 的方法都创建新对象
以下常见方法均符合这一原则(调用后原字符串不变,返回的是新字符串):
str.concat("suffix")str.substring(2, 5)-
str.replace('a', 'b')和str.replace("old", "new") -
str.toUpperCase()、str.toLowerCase() str.trim()-
str.strip()(Java 11+) -
str.replaceAll("regex", "rep")、str.replaceFirst("regex", "rep") -
str.split("delim")[0](split 返回 String[],但每个数组元素都是新 String)
不会返回 String 的方法(不产生新对象)
这些方法返回其他类型,或 void,它们不涉及字符串内容变更,自然也不返回新 String:
-
str.length()→ 返回int -
str.charAt(0)→ 返回char -
str.indexOf("x")→ 返回int -
str.contains("abc")→ 返回boolean -
str.startsWith("pre")、str.endsWith("suf")→ 返回boolean -
str.equals(other)、str.equalsIgnoreCase(other)→ 返回boolean -
str.compareTo(other)→ 返回int
特别注意:“+” 和 “+=” 也是创建新对象
字符串拼接操作符本质是编译器语法糖,底层调用 StringBuilder(或常量折叠优化),但最终结果仍是生成新 String:
-
String s = "a" + "b";→ 编译期优化为字面量"ab"(常量池中复用,但仍是独立对象) -
String s = "a"; s += "b";→ 运行时等价于s = new StringBuilder().append(s).append("b").toString();,必然新建对象
没有“返回原对象”的 public String 方法
String 类中不存在任何公开的、返回类型为 String 且实际返回 当前 this 引用 的方法。即使内容未变(比如 "abc".replace("d", "e")),它仍会返回原字符串的一个新引用(JVM 可能优化为同一常量池对象,但语义上仍是“新对象”,且不能依赖此行为)。
简言之:只要方法签名是 public String xxx(...),你就该默认它返回了一个逻辑上独立的新 String 实例。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











