如何证明 java 中的字符串作为引用类型?查看以下案例

How to justify Strings in java as reference type? check out the following cases

案例 1:

        String s1 = "Hello";
        String s2 = s1; //now has the same reference as s1 right?

        System.out.println(s1); //prints Hello
        System.out.println(s2); //prints Hello

        s1 = "hello changed"; //now changes s2 (so s1 as well because of the same reference?) to  Hello changed

        System.out.println(s1); //prints Hello changed 
        System.out.println(s2); //prints Hello  (why isn't it changed to  Hello changed?)

这个案例的输出是显而易见的。

案例 2:

        String s1 = "Hello";
        String s2 = s1; //now has the same reference as s1 right?

        System.out.println(s1); //prints Hello
        System.out.println(s2); //prints Hello

        s2 = "hello changed"; //now changes s2 (so s1 as well because of the same reference?) to  Hello changed

        System.out.println(s1); //prints Hello (why isn't it changed to Hello changed?)
        System.out.println(s2); //prints Hello changed

我想解决引用类型的困惑

之后

String s2 = s1;

s2s1 都引用了相同的 String

但是在

之后
s2 = "hello changed";

s2 持有对新 String 的引用,而 s1 仍然持有对原始 String.

的引用

String 是不可变的,因此您无法更改现有 String 对象的状态。为 String 变量分配一个新值只会使该变量引用一个新的 String 对象。原始 String 对象不受影响。

好吧,让我为您解决以上所有情况。

案例一:

当您创建 String s1 = "Hello"; 时,编译器首先将 String"Hello" 放入内存位置,并将该内存位置的引用存储到变量 s1。那么你的变量 s1 有什么?只有 "Hello" 的引用。所以 s1 不包含 Hello 而是它的内存位置作为参考。完成了吗?

然后当你声明 String s2 = s1; 时,你只存储 Hellos2 的引用而不是 s1 变量本身的引用,因为 s1"Hello" 的引用仅此而已。然后,当您同时打印 s1s2 时,它们都在打印 "Hello" 因为它们都包含 "Hello".

的引用

当您声明 s1 = "hello changed"; 时,s1 现在不再有 "Hello" 的引用,而是包含 String"hello changed" 的引用位于不同的内存位置。但是 s2 仍然具有 String"Hello" 的引用,因为您还没有为 s2 分配任何内容。所以现在 s1"hello changed" 的引用,s2"Hello" 的引用。如果您打印 s1s2,它们将打印相应的 String"hello changed" 和 '"Hello"`。你现在清楚了吗?如果还没有看到下面的代码示例:

String s1 = "Hello"; // s1 has reference of "Hello"
String s2 = s1; // Now s2 has reference of "Hello" not s1

System.out.println(s1); // Prints "Hello"
System.out.println(s2); // Prints "Hello"

s1 = "hello changed"; // Now s1 has reference of "hello changed" not "Hello" but still s2 has reference of "Hello" because you did not changed it.

System.out.println(s1); // Prints "hello changed" 
System.out.println(s2); // Prints "Hello" because you did not changed it.

案例二:

String s1 = "Hello"; // s1 has reference of "Hello"
String s2 = s1; // Now s2 has reference of "Hello" not s1

System.out.println(s1); // Prints "Hello"
System.out.println(s2); // Prints "Hello"

s2 = "hello changed"; // Now s1 has reference of "hello changed" not "Hello" but still s2 has reference of "Hello" because you did not changed it.

System.out.println(s1); // Prints "Hello" because you did not changed it.
System.out.println(s2); // Prints "hello changed" because you changed it.

如果还有不明白的,别忘了评论哦。谢谢。