Java中字符串不可变的逻辑

Java · 3 天前 · 7 人浏览

下面的代码中,字符串其实并没有变,变的只是s的指向。

// 字符串不可变
public class Main {
    public static void main(String[] args) {
        String s = "hello";
        System.out.println(s); // 显示 hello
        s = "world";
        System.out.println(s); // 显示 world
    }
}

2025-06-03T19:35:38.png

以及这段代码中,输出的是hello,因为从s = "hello" 开辟了hello这个字符串的空间,还有s指向了hello这个字符串;t=s,s是个指针指向的是字符串,所以t也指向hello,那么当s被赋值为world时,s的指针指向了world字符串,并不影响原先的t指针,所以打印t依旧是hello。

// 字符串不可变
public class Main {
    public static void main(String[] args) {
        String s = "hello";
        String t = s;
        s = "world";
        System.out.println(t); // t是"hello"还是"world"?
    }
}

参考地址

本站立足于美利堅合衆國,請讀者自覺遵守當地法律!如有違規,本站不承擔任何法律責任! This site is based in the United States of America, readers are requested to abide by local laws! If there are any violations, this site does not bear any legal responsibility! Theme Jasmine by Kent Liao