I. Illustration of string immutability in Java

Source: Internet
Author: User
Tags string methods

Here's a bunch of examples to illustrate the immutability of Java's string.

1. Declare a string

s = "abcd";



The s variable holds a reference to the string object, and the following arrows explain the reference to which object is saved.

2. Assign a string variable to another string variable.

s;


The string object cannot be changed to show 2 variables s2 Save the same referenced values, which point to the value of the same object.

3. connect string

s = s.concat("ef");


The variable s now holds a reference to the newly created Sting object.

Summarize:
Once a string is created in memory (heap), it cannot be changed. We should note that all the string methods do not change the string itself, but instead return a new string.

If we need a string that can be changed, then we can use StringBuffer (Translator Note: thread safe) or StringBuilder. Otherwise, every time a new string is created, it wastes a lot of garbage collection.

Here is an example of a StringBuilder application.

PublicStatic String readfiletostring ()Throws IOException {File dirs =New File ("."); String FilePath = Dirs.getcanonicalpath () + file.separator+"SRC" +file.separator+"Testread.java"; StringBuilder FileData =new StringBuilder (1000); new bufferedreader (new filereader (FilePath)); char[] buf = new char[1024] ; int numread = 0; while ((Numread = Reader.read (BUF))! =-1) {String readdata = string.valueof (BUF, 0, numread); Filedata.append (readdata); buf = new char[1024];} reader.close (); String returnstr = filedata.tostring (); System.out.println (RETURNSTR); return returnstr;}            

I. Illustration of string immutability in Java

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.