I. Illustration: the String in Java is non-mutable. javastring

Source: Internet
Author: User
Tags string methods

I. Illustration: the String in Java is non-mutable. javastring

Here are a bunch of examples to illustrate the immutable Java String.

1. Declare a String

String s = "abcd";



The s Variable saves the reference of the string object. The arrows below explain the reference of the object that is saved.

 

2. assign a value to a String variable to another String variable.

String s2 = s;


The String object is unchangeable. The 2 variable s2 stores the same referenced values, all of which point to the same object value.

 

3. Connect to String

 

s = s.concat("ef");


The variable s now stores references to the newly created sting object.

 

Summary:
Once a string is created in the memory (HEAP), it cannot be changed. We should note that all the String methods will not change a string, but return a new string.

If we need a string that can be changed, we can use StringBuffer or StringBuilder. Otherwise, a large amount of time is wasted on garbage collection every time a new string is created.

Here is an application example of StringBuilder.

public static String readFileToString() throws IOException {        File dirs = new File(".");        String filePath = dirs.getCanonicalPath() + File.separator+"src"+File.separator+"TestRead.java";         StringBuilder fileData = new StringBuilder(1000);//Constructs a string buffer with no characters in it and the specified initial capacity        BufferedReader reader = 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;    }

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.