Bootstrap

【Java】字符串内存池机制备忘

public class test {
    String c;
    public static void main(String[] args) {
        String x = new String("Hello");
        change(x);
        System.out.println(x);
        test t = new test();
        t.change2(x);
        System.out.println(x);
        
        t.c = "Hello";
        System.out.println(t.c);
        change(t.c);
        System.out.println(t.c);
        t.change2(t.c);

        t.change3();
        System.out.println(t.c);
    }

    public static void change(String x) {
        x = "World";
    }
    public void change2(String x) {
        x = "World2";
    }
    public void change3() {
        c = "World3";
    }
}

这说明,java中函数的传递都是值传递,都是建立一个对于变量的拷贝。使用一般的传递方法的静态函数或静态函数,都无法改变无论是函数成员还是一个字符串对象。

仅有change3自行改变成员才可以真正改变。

另外,可以使用StringBuilder。Java字符串变量指向字符串池中的字符串常量,直接对于字符串变量的改变是改变其指向,传值时无法改变原指向处的内容。而StringBuilder是指向一个确定的字符串,传值进去是一个地址,改变这个变量会改变其地址上的字符串。

;