A small example of the immutability of the string class in Java

Source: Internet
Author: User

In the Java language, the string class has immutability, that is, constant strings cannot be changed. The following is a small example of a simple demonstration of related concepts.

1  Public classTest {2      Public Static voidMain (String []args) {3String str1= "Hello";4 System.out.println (str1);5 Tell (STR1);6 System.out.print (STR1); 7     }8     9      Public Static voidTell (String str)Ten     { OneStr= "Main"; A     } -  -}

Output Result:

1 Hello 2 Hello

As can be seen from the output, the value of the str1 is not changed, because in the Java language, the data of the reference type is passed as a function parameter, although the method of passing the value is still used, but the data passed is a reference, passing the address of the "hello" str1 point to the Tell method, In the Tell method, the point of change is to just copy the STR1, at the start of the Tell method, str1 copy to Str2, and then, str2 points to "main", then the point of str1 has not changed, to the end of the Tell method, str1 output is still "Hello";

1  Public classTest {2     3      Public Static voidMain (String []args) {4String str1= "Hello";5 System.out.println (str1);6 7str1= "Main";8 System.out.print (STR1); 9     }Ten}

Output results

Hellomain

From the output, it seems that the value of str1 has been changed, but in fact it just turns STR1 's point from "Hello" to "Mian", and "Hello" string does not change.

A small example of the immutability of the string class in Java

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.