java

Java 参数的传递、String 相关知识点

2020-12-24  本文已影响0人  一颗浪星

参数传递问题:

小伙伴们先看看以下代码,在心里写下自己的答案:

public class Base {

    public static void main(String[] args) {
        StringBuffer s = new StringBuffer("hello");
        StringBuffer s2 = new StringBuffer("hi");
        test(s, s2);
        System.out.println("方法調用后s的值:" + s);
        System.out.println("方法調用后s2的值:" + s2);
    }

    static void test(StringBuffer s3, StringBuffer s4) {
        System.out.println("方法初始化時s3的值:" + s3);
        System.out.println("方法初始化時s4的值:" + s4);
        s4 = s3;
        s3 = new StringBuffer("new");
        System.out.println("第一步变化后s3的值:" + s3);
        System.out.println("第一步变化后s4的值:" + s4);
        s3.append("boy");
        s4.append("gril");
        System.out.println("第二步变化后s3的值:" + s3);
        System.out.println("第二步变化后s4的值:" + s4);

    }

}

执行结果为:

方法初始化時s3的值:hello
方法初始化時s4的值:hi
第一步变化后s3的值:new
第一步变化后s4的值:hello
第二步变化后s3的值:newboy
第二步变化后s4的值:hellogril
方法調用后s的值:hellogril
方法調用后s2的值:hi

以上代码摘录自以下链接,我觉得挺不错的,把参数的传递讲的很详细,一起看看呗。

https://blog.csdn.net/weixin_43030796/article/details/81974190?utm_medium=distribute.pc_relevant_t0.none-task-blog-BlogCommendFromMachineLearnPai2-1.control&depth_1-utm_source=distribute.pc_relevant_t0.none-task-blog-BlogCommendFromMachineLearnPai2-1.control

String 相关知识点:

同样的我们先来看一段代码:

public class Mytest {

    public static void main(String[] args) {
        String ss = "a";
        String s2 = ss + "b" + "c";

        String s1 = "a" + "b" + "c";
        String s3 = "abc";
        System.out.println((s1 == s2));
        System.out.println((s1 == s3));
        test(s3);
        System.out.println("main 里面的 hashCode :" + s3.hashCode());
    }

    private static void test(String s) {
        System.out.println("改变前 hashCode:" + s.hashCode());
        s += s;
        System.out.println("改变后的值:" + s);
        System.out.println("改变后 hashCode:" + s.hashCode());
    }
}

执行结果为:
false
true
改变前 hashCode:96354
改变后的值:abcabc
改变后 hashCode:-1424388928
main 里面的 hashCode :96354

如果和你想的答案不一样,可以先看看这篇文章:
https://www.iteye.com/topic/634530

当"+"两端均为编译期确定的字符串常量时,编译器会进行相应的优化,直接将两个字符串常量拼接好,所以:s1 == s3

而 s2 是在堆中生成新的对象,所以:s1 != s2

上一篇 下一篇

猜你喜欢

热点阅读