总结一下传值和引用碰到的一下小问题。
运行下面两段代码,为什么结果不同。
public class Test {
public static void test(StringBuffer str) {
str.append(", World!");
}
public static void main(String[] args) {
StringBuffer string = new StringBuffer("Hello");
test(string);
System.out.println(string);
}
}
运行结果是:Hello, World!
public class Test {
public static void test(String str) {
str = "world";
}
public static void main(String[] args) {
String string ="Hello";
test(string);
System.out.println(string);
}
}
运行结果是:Hello
参考链接http://blog.youkuaiyun.com/yirentianran/article/details/2871417 总结一下结论。
String:
是对象不是原始类型.
为不可变对象,一旦被创建,就不能修改它的值.
对于已经存在的String对象的修改都是重新创建一个新的对象,然后把新的值保存进去.
String 是final类,即不能被继承.
StringBuffer:
是一个可变对象,当对他进行修改的时候不会像String那样重新建立对象
它只能通过构造函数来建立,
StringBuffer sb = new StringBuffer();
note:不能通过付值符号对他进行付值.
sb = "welcome to here!";//error
对象被建立以后,在内存中就会分配内存空间,并初始保存一个null.向StringBuffer
中付值的时候可以通过它的append方法.
sb.append("hello");
根据上面的内容我的理解是:
public class Test {
public static void test(String str) {
str = "world";//3.这时候并不是改变string堆中的值,而是在堆中新开辟了一个空间,存放world。
}
public static void main(String[] args) {
String string ="Hello";//1.创建了一个新对象,栈中存放了string指向堆的地址,堆中新开辟了一个空间存放内容"hello"
test(string);//2.将string的值传进去
System.out.println(string);//4.回到这里来的时候,栈中存放的string地址并没有改变,还是指向原来的地址,堆中的内容也没有变,存放的是hello.
}
}
至于第二段代码我的理解是:
<pre name="code" class="java"> public class Test {
public static void test(StringBuffer str) {
str.append(", World!");//3.这时候是在原来的str上添加了",world",堆中的内容被改成了“hello,world"。
}
public static void main(String[] args) {
StringBuffer string = new StringBuffer("Hello");<pre name="code" class="java"> //1.创建了一个新对象,栈中存放了string指向堆的地址,堆中新开辟了一个空间存放内容"hello"
test(string);//2.将string的值传进去
System.out.println(string);
}
}
---------------------- ASP.Net+Unity开发、 .Net培训、期待与您交流! ----------------------