A deep understanding of the differences between string, StringBuffer, and StringBuilder in Java

Source: Internet
Author: User
Tags stringbuffer

Disclaimer: This blog is an original blog, without consent. No reprint! Small partners assume that it is seen elsewhere, suggest or csdn to see (link to http://blog.csdn.net/bettarwang/article/details/26412497), see the code and ask questions, Discussions are more convenient.

Start by simply combing through the meanings of string, StringBuffer, and StringBuilder in Java.

1.String class

First of all. It is thread-safe and can be used in multithreaded programming.

Second, the object of the string class is immutable, that is, defined at the time of definition, like string str= "Hello"; str+= "Java"; The statement actually generates a new object, just that we are unaware of it. Note, however, that a large number of strings are consumed when new objects are created. It is important to consider using StringBuffer or StringBuilder, otherwise it will greatly reduce the efficiency of the program.

2.StringBuffer class:

First, it's also thread-safe.

Second, it is a mutable class, and the manipulation of the string it points to does not produce new objects. Each StringBuffer object has a certain buffer capacity, and when the string size does not exceed the capacity, no new capacity is allocated, and when the string size exceeds the capacity, the capacity is added on its own initiative. So it's more efficient than string.

the two most frequently used methods of the StringBuffer class are the Append and insert methods, StringBuffer have overloaded these methods to accept arbitrary types of data, so the small partners. If Strbuffer is an object of StringBuffer. So like Strbuffer.append (3.14f); Strbuffer.append (true); This statement is completely legal .

3.StringBuilder class:

First, it is not thread-safe. That can only be used in single-threaded programming.

Secondly. It is similar to StringBuffer, where the object is also a variable sequence of characters. However, it is important to note that it is constructed in the following ways:

StringBuilder (): Creates a StringBuilder object with a capacity of 16.

StringBuilder (int capacity): Creates a StringBuilder object with a capacity of capacity;

StringBuilder (String s): Creates a StringBuilder object that includes S. Add 16 empty elements at the end of the same time.

         stringbuilder (charsequence CS): Create a StringBuilder object that includes CS, append 16 empty elements at the end;   

All in all. Thread synchronization. String and StringBuffer are thread-safe, and StringBuilder are not thread-safe; stringbuilder>stringbuffer>string in operational efficiency, Therefore, in the need of a large number of string manipulation of single-threaded occasions, should be used day StringBuilder to improve efficiency, in a large number of string operation of multi-threaded case, StringBuffer is undoubtedly the best choice. For single-threaded or multithreaded situations where a small number of string operations are used, string is simpler and more convenient.

The above three classes have been combed, but this is only the basic knowledge, there is no deep understanding. Taking such a topic is not trying to impress. Let's start with some of my own experiences and talk about my own understanding.

As we all know, the object of the string class is immutable. However, considering that "everything is quoted" in Java, it is possible to change the value by passing a string reference in the function. Thus often the following such errors are committed:

Import Java.util.*;import java.io.*;p ublic class stringtest{   private static void treatstring (String str)   {     if (str.contains ("Hello"))     {       str= "Hello java";     }     else     {       str= "enjoy Java";     }   }   public static void Main (String[]args)   {      String str1= ' Hello World ';      String str2= "study Java";      Treatstring (STR1);      Treatstring (STR2);            System.out.println (STR1);      System.out.println (STR2);   }}         

The output results are as seen in:


originally expected to pass the reference to change the value of the string str1 and str2, but from the output of the value of the string is not changed at all, this is why?

It turns out that a reference is actually passed. However, unlike normal objects, the treatstring (String) function does not make any changes to the object that Str points to (or to the memory address that Str points to). Instead, a new string object is created. But this new object is just a tangible reference to it, and the actual participation does not point to it. In fact, throughout the process, the actual STR always points to the object that started the most. So it is not difficult to understand why this output results.

So what if you want to get the effect of a generic object passing a reference?

very easy, the first method, also my personal recommended method, is the return value string instead of void , the code above will be changed to:

Import Java.util.*;import java.io.*;p ublic class stringtest{   //private static void treatstring (String str)    private static string treatstring (String str)   {     if (str.contains ("Hello"))     {       str= "Hello java";     }     else     {       str= "enjoy Java";     }          return str;   }   public static void Main (String[]args)   {      String str1= ' Hello World ';      String str2= "study Java";      Str1=treatstring (STR1);      Str2=treatstring (STR2);            System.out.println (STR1);      System.out.println (STR2);   }}         
At this point the output results are as seen as:



Obviously. At this point, we have achieved our intended purpose.

when I come here, I will combine my own experience, that is, the beginning of the String.Replace (Oldchar,newchar), this function is not familiar. It is thought that the change of STR can be realized simply by invoking it (i.e., the direct str.replace (Oldchar,newchar), the change of STR can be achieved), and actually using its return value ability to change str, i.e. str=str.replace (OldChar, Newchar) is the right thing to do.

Another way, of course, is to use StringBuffer and StringBuilder, because they are object-changeable.

A detailed sample is appended to the back. Let's write it down here today.

Good night, little friends!   

A deep understanding of the differences between 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.