String和StringBuffer的参数传递问题详解

首先仔细的看一下下面的源代码:

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

为什么是这样的结果,我是这样分析的:(下图的数字代表代码中的步骤)

13859457-ce39efbcb323d362.png
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);
    }
}
13859457-698c871b95b8297f.png

上面代码的结果主要是表达了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

13859457-e6e33e72035d0ea2.png

总结:在引用数据类型的传递时候应该注意特别注意,我们应该避免避免赋值运算符的使用,如果要使用也应该特别注意。

因为String类的特点:String字符串是不可改变的。所以我们在用String作为参数传递的时候可以把String类作为基本的数据类型看待。

猜你喜欢

转载自blog.csdn.net/weixin_34342207/article/details/88100833