String和StringBuffer的参数传递问题详解
2019-02-03 本文已影响0人
_AlphaBaby_
首先仔细的看一下下面的源代码:
public class DemoTestStringBuffer {
public static void main(String[] args) {
String s1 = "hello";
String s2 = "world";
System.out.println("s1:" + s1 + "\ns2:" + s2 );
change(s1, s2);
System.out.println("s1:" + s1 + "\ns2:" + s2);
}
public static void change(String str1, String str2) { //步骤1,2
str1 = str2;//步骤3
str2 = str1 + str2; //步骤4
}
}
输出结果:
s1:hello
s2:world
s1:hello
s2:world
为什么是这样的结果,我是这样分析的:(下图的数字代表代码中的步骤)

public class DemoTestStringBuffer {
public static void main(String[] args) {
String s1 = "hello";
String s2 = "world";
String s3 = "helloworld";
String s4 = s1+s2;
String s5 = "hello"+"world";
System.out.println(s3 == s4);
System.out.println(s3 == s5);
}
}

上面代码的结果主要是表达了s1+s2与"hello"+"world"的区别,具体为什么是这样的结果可以看我再文章:java-String类(1)中的解释。根据上面的结果我们再来理解下面的代码。
public class DemoTestStringBuffer {
public static void main(String[] args) {
StringBuffer s1 = new StringBuffer("hello");
StringBuffer s2 = new StringBuffer("world");
System.out.println("s1:" + s1 + "\ns2:" + s2 );
change(s1, s2);
System.out.println("s1:" + s1 + "\ns2:" + s2);
}
public static void change(StringBuffer str1, StringBuffer str2) {
str1 = str2;
str2.append(str1);
System.out.println("change内部str1:"+str1);
}
}
输出结果:
s1:hello
s2:world
change内部str1:worldworld
s1:hello
s2:worldworld

总结:在引用数据类型的传递时候应该注意特别注意,我们应该避免避免赋值运算符的使用,如果要使用也应该特别注意。
因为String类的特点:String字符串是不可改变的。所以我们在用String作为参数传递的时候可以把String类作为基本的数据类型看待。