String, StringBuffer, and StringBuilder in Java

Source: Internet
Author: User

Yesterday, I encountered a programming question about the substitution of character contents in a string, the topic is as follows:
Implement a function that replaces a space in a string with "%20". For example, when the string is we are Happy. The string after substitution is we%20are%20happy.
public class Solution {public    String replacespace (StringBuffer str) {    //Add code    }}

So I want to use this question to understand the definition and processing of strings in Java.

A, String

There is no built-in string type in Java, a predefined class string class in the standard Java class Library, and all double quotes represent an instance of the string class. A character array value is defined in the string class to store the string. The source code is as follows:

Private Final char value[];...public String () {        this.value = new char[0];}
The value array is defined as final and can be seen in the simplest creation string object method of many constructors of the string class, that is, the storage string array value is initialized with a length of 0.
A character array defined as a final type value is therefore also unique: The final member variable represents a constant and can only be assigned once, and the value will no longer change after the assignment. An array, as a special type of variable (reference type), is in memory by the array variable name in the stack memory pointing to the array value stored in the heap memory. One of the characteristics of heap memory includes the default initialization operation, and the default initialization value of type int is 0,char default initialization value is '. That is, once a string has been created, its value cannot be changed.
String str = "xuwenping"; str = str + "123";

The above two lines of code, the surface looks like string str and the variable is meaningless, its value can be changed. Its actual operation at the code level is that the first line is to create a reference variable of string in stack memory str, create the string "Xuwenping" in Heap Memory, ("xuwenping" string is actually stored as a character array), and Str points to "xuwenping" as a string pointer First address (the first address of the array). The second line creates a new string "xuwenping123" in heap memory and points str to the value of the new string. The original "xuwenping" string is no reference and will be garbage collected by the JVM.

As mentioned above, the value of the string is immutable. If it changes, it creates a new string. The creation process is inevitably inefficient and, of course, the Java designer implements another way of assigning string objects in the hope of eliminating inefficiencies: the string shared pool (buffer pool). Buffer pool is Java in order to save memory space, in memory will create a specially designed for string buffer pool, used to save the existing string, if the 2 string is the same, use the string in the pool, the new object is no longer created.

String str1 = "abc";   String str2 = "abc";   System.out.println (STR1==STR2); TrueString str3 =new String ("abc");   String STR4 =new string ("abc");   System.out.println (STR3==STR4); False  

String str = "Hello";
This method creates a "Hello" string, and the JVM's character cache pool also caches the string.
String str = new string ("Hello");
At this point the program, in addition to creating a string, str refers to the bottom of the string object also contains a char[] array, the char[] array is stored in turn h,e,l,l,o

Second, StringBuffer

Java provides a variable string class StringBuffer because the string changes cause the creation of new strings to be inefficient. StringBuffer inherits the Abstractstringbuilder class. Its default initialization operation is as follows:

    Public StringBuilder () {        super (+);    } ...      Abstractstringbuilder (int capacity) {        value = new char[capacity];    }    Char[] value;

StringBuffer initialization calls the parent class construction method, the parent class has a non-final member variable char[] value, and the default is to create a character array of length 16. As the number of characters increases, StringBuffer automatically increases, viewing the source discovery, calling the Expandcapacity method of the parent class and invoking the Copyof method in the Java.util.Arrays array tool class to create a new size of value.length * An array of 2 + 2 and copies the original array characters into a new array of values. Thus the arbitrary change of the string is realized.

void expandcapacity (int minimumcapacity) {        int newcapacity = value.length * 2 + 2;        if (newcapacity-minimumcapacity < 0)            newcapacity = minimumcapacity;        if (Newcapacity < 0) {            if (minimumcapacity < 0)//overflow                throw new OutOfMemoryError ();            newcapacity = Integer.max_value;        }        Value = arrays.copyof (value, newcapacity);    }

Third, StringBuilder

Starting with java1.5, StringBuilder began to appear, and the API documentation describes the following: "This class is designed as StringBuffer a simple replacement for use by a single thread in a string buffer (which is common)." This sentence contains two meanings: first, it has the characteristics of StringBuffer: It can be expanded with the increase of the storage string elements, the second is that StringBuffer is multi-threaded synchronization, and StringBuilder is not synchronized with multithreading.

View the source code and find the process by StringBuilder: Append->abstractstringbuilder.append->ensurecapacityinternal Expandcapacity Arrays.copyof, it is found that both call the Expandcapacity method of the parent class and call the CopyOf method in the Java.util.Arrays array tool class to create a new array of size Value.length * 2 + 2. The original array character is copied into the new array in order to realize the expansion nature.

And in the multi-threaded aspect, the view source to see StringBuffer except the constructor outside the other method all realizes the lock synchronization with the synchronized, but StringBuilder is always the bare Ben. In "Java Core Volume One: basic knowledge" has the following assertion: In jdk5.0 introduced the StringBuilder class. The predecessor of this class is StringBuffer, which is slightly less efficient, but allows the operation of adding or removing characters in a multithreaded manner. If all strings are edited in a single thread (which is usually the case), you should replace it with StringBuilder. The APIs for these two classes are the same.

Iv. Solutions

Finally, answer the question that leads to this topic:

public class Solution {public    String replacespace (StringBuffer str) {        String stri = str.tostring ();        Stri = Stri.replaceall ("", "%20");        return stri;}    }

StringBuffer, StringBuilder can be converted to sting object by ToString method.

  

String, StringBuffer, and StringBuilder 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.