Home  >  Article  >  Java  >  How to prove that string is immutable in java

How to prove that string is immutable in java

王林
王林forward
2023-04-29 08:46:121455browse

How to prove that strings are immutable

I have written two articles about the immutability of strings, and I almost vomited by the end. But there are still some students who don't understand. Every once in a while, someone sends me a private message, and I have to put the previous article in my favorites. When asked, I will send him the link.

There are many factors that cause this confusion. For example, is Java passed by value or by reference? What is the string constant pool?

I have to talk about it again this time, although I’m so fed up, but I still have to prove it!

public class StringImmutabilityTest {     public static void main(String[] args) {         String s1 = "沉默王二";         String s2 = s1;         System.out.println(s1 == s2);          s1 = "沉默王三";         System.out.println(s1 == s2);          System.out.println(s2);     } }

The output is as follows:

true false 沉默王二

1)String s1 = "Silent Wang Er", Java creates " in the string constant pool The object of the string of characters "Silent King 2", and assign the address reference to s1

2)String s2 = s1, s2 and s1 point to the same address reference - the "silent one" in the constant pool Wang Er".

So, at this time s1 == s2 is true.

3)s1 = "Silent Wang San", Java creates an object of the string "Silent Wang San" in the string constant pool, and assigns the address reference to s1, but s2 still points to " The address reference of the string object "Silent King II".

So, at this time, s1 == s2 is false, and the output result of s2 is "Silent Wang Er", which proves that the string is immutable.

The above is the detailed content of How to prove that string is immutable in java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete