string “+” 操作就是根据 StringBuilder (或 StringBuffer )类及其 append 方法实现的。 <?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

String 不可变其实就是说一个 String 对象创建之后不能再在这个对象上做其他操作(如追加,删除一个字符),只能通过创建别的 String 对象来获取这个效果,而 StringBuilder 就可以在一个 StringBuilder 对象上进行改变:

String  str = hello

str = str+ world // 这时并不是在原来的 hello ”对象 上追加 world ,而是重新创建了一个 hello world ”对象

 

String 不能被修改,事实上很简单。就是因为 String 没有提供写操作方法,没有提供能够修改 String 对象的成员变量的方法。而 StringBuilder 则提供了这样的方法( append ()等方法)。

也许有人会说 String 不是有个 concat 方法可以在字符串后面追加字符串吗?呵呵,我们看过 API 的解释就知道是怎么回事了:

Concat

public String concat(String str)

将指定字符串联到此字符串的结尾。

如果参数字符串的长度为 0,则返回此 String 对象。否则,创建一个新的 String 对象,用来表示由此 String 对象表示的字符序列和由参数字符串表示的字符序列串联而成的字符序列。

对了,区别就在于 String 的调用 concat 方法会新建立一个 String 对象,而 StringBuilder append 方法返回的还是原来对象的应用。
public class TestValue {
  public static void main(String[] args) {
    String string = new String("Hello");
    modify(string);
    System.out.println(string);
  }
  public static void modify(String s) {
    s += "world!";//这里通过"+"操作创建了一个新对象让s指向它。但string的引用并没有变。
    s = s.concat("winwin");//这里的concat方法重新创建了一个String对象,所以string的引用没有变,只是s的引用变了。
  }
}
 
 
public class TestValue {
  public static void main(String[] args) {
    StringBuilder string = new StringBuilder("Hello");
    modify(string);
    System.out.println(string);
  }
  public static void modify(StringBuilder s) {
    s.append(",world!");//由于StringBuilder类有方法可以改变,所以就能够改变string的值。
  }
}
 
 
此篇文章为我自己写的笔记,既然是笔记,顺便再写一点与题目无关的内容:

String str = winwin

String str = new String(winwin)

的区别:

字符串直接赋值时,String类型的变量所引用的值是存储在类的常量池中的。这种情况下,变量的内存空间大小是在编译期就已经确定的。

new对象的方式是将 winwin存储到String对象的内存空间中,而这个存储动作是在运行期进行的。