前段时间,一位在面试过后同学问我,以下代码输出是什么?被他这样一问,我逆向思维告诉我答案是"Hello"。
实际运行答案的确如此,带着好奇心究其因。才发现这道题考我对String,直接使用"+",会新建新的String对象,这段代码add里str实际会引用新的对象,改变另一引用空间值,而对于main里str引用空间值并为改变。如果采用StringBuffer,则不然。
欢迎多多交流 46773217(群)
public class A{
public static void add(String str,String str1){
str+=str1;
}
public static void main(String args[]){
String str="Hello";
String str1="World";
add(str,str1);
System.out.println(str)
}
}
实际运行答案的确如此,带着好奇心究其因。才发现这道题考我对String,直接使用"+",会新建新的String对象,这段代码add里str实际会引用新的对象,改变另一引用空间值,而对于main里str引用空间值并为改变。如果采用StringBuffer,则不然。
public class A {
public static void add(StringBuffer str, StringBuffer str1) {
str.append(str1);
}
public static void main(String args[]) {
StringBuffer str = new StringBuffer("Hello");
StringBuffer str1 = new StringBuffer("World");
add(str, str1);
System.out.println(str);
}
}
欢迎多多交流 46773217(群)