Java – if string objects are interned, why does changing one affect others

See English answers > what is the difference between a variable, object, and reference? 5

public class EqualExample {
public static void main(String[] args) {

    String str = new String("Hello");
    String str1 = new String("Hello");

    System.out.println(str == str1);
    System.out.println(str1.equals(str));

}

}

The output of the above program will be

False real

public class EqualExample {
    public static void main(String[] args) {

    String str = "Hello";
    String str1 = "Hello";

    System.out.println(str == str1);
    System.out.println(str1.equals(str));

}

}

The output of the above code is

Really, really

This is because heloo Alred exists in the string pool, so it is actually a string and references the same object. Then why if I change STR1 to "Hello Java", then why does STR still have the value "hello" Because they refer to the same object, the value of STR must change the public class equalexample {public static void main (string [] args){

String str = "Hello";
    String str1 = "Hello";

    System.out.println(str == str1);
    System.out.println(str1.equals(str));

    str1="Heloo java";
    System.out.println(str+str1);
    System.out.println(str == str1);
    System.out.println(str1.equals(str));

}

}

The output is true and true heloo Java is false

Solution

STR1 is not a string It is a reference to a string object By doing

str1 = "Heloo java";

You didn't modify the string object, you just pointed the reference to a different string object

Before:

str --------> "Hello"
                ^
str1 -----------|

After:

str --------> "Hello"

str1 -------> "Heloo Java"

Changing objects will include doing similar things

str1.setCharacters("Heloo Java");

But such a method does not exist because the string is immutable Therefore, their characters cannot be modified (unless dirty reflection techniques are used)

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>