On the usage of StringBuilder in Java _java

Source: Internet
Author: User
Tags stringbuffer

The string object is immutable. Each time you use one of the methods in the System.String class, you create a new string object in memory, which requires a new space to be allocated for the new object. The system overhead associated with creating a new string object can be expensive when you need to perform repeated modifications to the string. If you want to modify a string without creating a new object, you can use the System.Text.StringBuilder class. For example, when you concatenate many strings together in a loop, using the StringBuilder class can improve performance.

By initializing a variable with an overloaded constructor method, you can create a new instance of the StringBuilder class, as illustrated in the following example.

StringBuilder Mystringbuilder = new StringBuilder ("Hello world!");

(i) Set capacity and length

Although the StringBuilder object is a dynamic object that allows you to expand the number of characters in the string it encapsulates, you can specify a value for the maximum number of characters it can hold. This value is called the capacity of the object and should not be confused with the length of the string that the current StringBuilder object holds. For example, you can create a new instance of the StringBuilder class with the string "Hello" (length 5), and you can specify that the object's maximum capacity is 25. When StringBuilder is modified, it does not reallocate space for itself until capacity is reached. When capacity is reached, new space is automatically allocated and the capacity doubles. You can use one of the overloaded constructors to specify the capacity of the StringBuilder class. The following code example specifies that the Mystringbuilder object can be expanded to a maximum of 25 blanks.

Stringbuildermystringbuilder = new StringBuilder ("Hello world!", 25);

Alternatively, you can use the Read / Write Capacity property to set the maximum length of the object. The following code example uses the Capacity property to define the maximum length of an object.

Mystringbuilder.capacity= 25;

(ii) Several common methods of this type are listed below:

(1) The Append method can be used to add the string representation of text or an object to the end of the string represented by the current StringBuilder object. The following example initializes a StringBuilder object to "Hello world" and appends some text to the end of the object. Space is allocated automatically as needed.

Stringbuildermystringbuilder = new StringBuilder ("Hello world!");
Mystringbuilder.append ("What a Beautiful Day.");
Console.WriteLine (Mystringbuilder);

This example will Hello world! What abeautiful Day. Displayed to the console.

(2) The AppendFormat method adds text to the end of the StringBuilder and implements the IFormattable interface, so you can accept the standard format strings described in the Format section. You can use this method to customize the format of a variable and append those values to the back of the StringBuilder. The following example uses the AppendFormat method to place an integer value formatted as a currency value into the end of StringBuilder.

int myint=;
StringBuilder Mystringbuilder = new StringBuilder ("Your Total is");
Mystringbuilder.appendformat ("{0:c}", MyInt);
Console.WriteLine (Mystringbuilder);

This example displays the Your total is $25.00 to the console.

(3) The Insert method adds a string or object to the specified position in the current StringBuilder. The following example uses this method to insert a word into the sixth position of the StringBuilder.

Stringbuildermystringbuilder = new StringBuilder ("Hello world!");
Mystringbuilder.insert (6, "Beautiful");
Console.WriteLine (Mystringbuilder);

This example displays the Hello beautifulworld! to the console.

(4) You can remove a specified number of characters from the current StringBuilder using the Remove method, starting at the specified zero-based index. The following example uses the Remove method to shorten the StringBuilder.

Stringbuildermystringbuilder = new StringBuilder ("Hello world!");
Mystringbuilder.remove (5,7);
Console.WriteLine (Mystringbuilder);

This example displays hello to the console.

(5) Using the Replace method, you can replace the characters within the StringBuilder object with another specified character. The following example uses the Replace method to search for the StringBuilder object, find all the exclamation characters (!), and use the question mark character (?). To replace them.

Stringbuildermystringbuilder = new StringBuilder ("Hello world!");
Mystringbuilder.replace ('! ', '? ');
Console.WriteLine (Mystringbuilder);

This example shows Hello world to the console

Getsqlmapclienttemplate (). queryForList (New StringBuilder ()). Append (Entityclass.getname ()). Append (". Select"). ToString (), NULL);

Java StringBuilder class

If the program has a high demand for additional strings, it is not recommended to use + for concatenation of strings. Consider using the Java.lang.StringBuilder class, which produces an object that has a length of 16 characters by default, and you can specify the initial length yourself. If the attached character exceeds the length that can be accommodated, the StringBuilder object automatically increases the length to accommodate the appended characters. If there are frequent strings attached requirements, using the StringBuilder class can greatly improve the efficiency. The following code:

Java code

public class Appendstringtest {public static void main (string[] args) {String text = "";  
          Long begintime = System.currenttimemillis ();  
          for (int i= 0;i< 10000; i++) Text = text + i;  
          Long endtime = System.currenttimemillis ();  
  
          System.out.println ("Execution Time:" + (Endtime-begintime));  
          StringBuilder sb = new StringBuilder ("");  
          BeginTime = System.currenttimemillis ();  
          for (int i= 0;i< 10000 i++) sb.append (string.valueof (i));  
          Endtime = System.currenttimemillis ();  
  
      System.out.println ("Execution Time:" + (Endtime-begintime));
        
          } public class Appendstringtest {public static void main (string[] args) {String text = "";
          Long begintime = System.currenttimemillis ();
          for (int i=0;i<10000;i++) Text = text + i; Long Endtime = System.currentTimemillis ();

          System.out.println ("Execution Time:" + (Endtime-begintime));
          StringBuilder sb = new StringBuilder ("");
          BeginTime = System.currenttimemillis ();
          for (int i=0;i<10000;i++) sb.append (string.valueof (i));
          Endtime = System.currenttimemillis ();

      System.out.println ("Execution Time:" + (Endtime-begintime)); 
 }
}

This section of code output:

Execution Time: 3188

Execution time: 15

StringBuilder is the j2se1.5.0 new class, before the version of the same requirements, then use Java.util.StringBuffer. In fact, StringBuilder is designed to have the same operating interface as StringBuffer. Using StringBuilder in the case of a stand-alone non-threading (multithread) can be more efficient because StringBuilder does not handle synchronization problems. StringBuffer handles synchronization issues, and if StringBuilder is manipulated under multiple threads, use StringBuffer instead to allow the object to manage the synchronization problem itself.

The above analysis of Java in the use of StringBuilder is a small series to share all the content, hope to give you a reference, but also hope that we support the cloud-dwelling community.

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.