這是一道關於string的問題,論壇文章的地址:http://blog.csdn.net/steedhorse/article/details/6892569
我在這裏做下擴展:
首先看下程序:
package com.tmaic.test;
public class StringTest {
public static void main(String args[]) {
String s = new String("Hello");
System.out.println(s);
foo(s);
System.out.println(s);
}
public static void foo(String s) {
s = new String("World");
}
}
輸出結果:
Hello
Hello
程序變一下:
package com.tmaic.test;
public class StringTest {
public static void main(String args[]) {
String s = new String("Hello");
System.out.println(s);
foo(s);
System.out.println(s);
}
public static void foo(String s) {
//s = new String("World");
s = "World";
}
}
大家想會輸出什麼呢?
輸出結果:
Hello
Hello
爲什麼會這樣?
那再變一下程序:
package com.tmaic.test;
public class StringTest {
public static void main(String args[]) {
StringBuffer s = new StringBuffer("Hello");
System.out.println(s);
foo(s);
System.out.println(s);
}
public static void foo(StringBuffer s) {
//s = new String("World");
s = s.append( "World");
}
}
這次結果是:
Hello;
HelloWorld;
參考這篇文章應該很好理解:http://blog.csdn.net/tmaic/article/details/6799271
Java語言幾乎一切皆引用的特點起作用了,首先new 一個string很好理解,開闢了新的空間,foo(s)傳遞的是s的引用,在這個方法中又new了s,由於string字符不可變,所以他新建了一個引用,這時候如果你在foo()方法體裏打印s你會得到結果"world";所以現在就存在兩個引用,如果把foo的方法傳參改爲a的話會好理解點