在Java中更改字符串值

Kra*_*ken 1 java string immutability

我有

String newStr = "previous"
Run Code Online (Sandbox Code Playgroud)

过了一段时间我想把我的字符串改成next.我现在能做到

newStr=getNewString(); // Say getNewString return `next`
Run Code Online (Sandbox Code Playgroud)

Arent字符串应该是不可变的.

我能用其他任何方式实现这个目标吗 谢谢.

编辑:neww代替new

Pet*_*rey 12

Arent字符串应该是不可变的.

字符串是不可变的.

对String的引用不必是不可变的.

String s = "hello";
s = "World"; // the reference s changes, not the String.

final String t = "Hi"; // immutable reference
t = "there"; // won't compile.

// immutable reference to a mutable object.
final StringBuilder sb = new StringBuilder();
sb.append("Hi"); // changes the StringBuilder but not the reference to it.
sb = null; // won't compile.
Run Code Online (Sandbox Code Playgroud)