Stringbuffer 有append()方法
Stringbuffer其实是动态字符串数组
append()是往动态字符串数组添加,跟“xxxx”+“yyyy”相当那个‘+’号
跟String不同的是Stringbuffer是放一起的
String1+String2 和Stringbuffer1.append("yyyy")虽然打印效果一样,但在内存中表示却不一样
String1+String2 存在于不同的两个地址内存
Stringbuffer1.append(Stringbuffer2)放再一起
1. public class Foo {
2. public static void main (String [] args) {
3. StringBuffer a = new StringBuffer (“A”);
4. StringBuffer b = new StringBuffer (“B”);
5. operate (a,b);
6. system.out.printIn{a + “,” +b};
7. }
8. static void operate (StringBuffer x, StringBuffer y) {
9. x.append {y};
10. y = x;
11. }
12. }
What is the result?
A. The code compiles and prints “A,B”.
B. The code compiles and prints “A,A”.
C. The code compiles and prints “B,B”.
D. The code compiles and prints “AB,B”.
E. The code compiles and prints “AB,AB”.
F. The code does not compile because “+” cannot be overloaded for StringBuffer.
答案: D
StringBuffer a=new StringBuffer("A");
//这一行,假设a指向了内存地址为4000的地方
StringBuffer b=new StringBuffer("B");
//这一行,假设b指向了内存地址为5000的地方
method(a,b);
//这个方法只是把a和b的地址传了过去。x指向4000,y指向5000,a与b还是指向原来的地址。
x.append(y);
//这句将a指向地址的内容变了。
y=x
//只是将y指向的地址发生变化,变为4000,而main程序中的b还指向5000