Get the App
SLTechnology News&Howtos  ›  Development  › 

How does java prove that strings are immutable

Shulou Source: shulou.com Published: 2022-06-01 05:14:45 09月15日 Update

This article mainly introduces java how to prove that the string is immutable, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let the editor take you to understand it.

How to prove that a string is immutable

I've written two articles about the immutability of strings, and I'm going to throw up at the end of it. But there will still be some students do not understand, after a while, someone privately believe me, I have to put the previous article in the favorites, when asked, I will send him the link.

There are many factors causing this confusion, for example, is Java value passing or reference passing? What is a string constant pool?

This time I have to talk about it again. Although I am bored, I still have to prove it.

Public class StringImmutabilityTest {public static void main (String [] args) {String S1 = "Silent King II"; String S2 = S1; System.out.println (S1 = = S2); S1 = "Silent King III"; System.out.println (S1 = = S2); System.out.println (S2);}}

The output is as follows:

True false Silent King II

1) String S1 = "Silent King II". Java creates an object with the character "Silent King II" in the string constant pool and assigns the address reference to S1.

2) String S2 = S1 Magazine S2 and S1 point to the same address reference-the "Silent King II" in the constant pool.

Therefore, S1 = = S2 is true at this time.

3) S1 = "Silent King 3", Java creates an object of the string "Silent King 3" in the string constant pool and assigns the address reference to S1, but S2 still points to the address reference of the character object of "Silent King II".

Therefore, at this time S1 = = S2 is the output of false,s2 as "Silent King II", which proves that the string is immutable.

Thank you for reading this article carefully. I hope the article "how to prove that a string is immutable" shared by the editor will be helpful to everyone. At the same time, I also hope that you will support and follow the industry information channel. More related knowledge is waiting for you to learn!

Tags: Character string variable article address constant object point result creation output confusion reason value interest classmate at the same time factor article time Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Redmi Apple Huawei NVidia macOS