Java StringBuffer Class (reprinted) ____ Very important a class, thread-safe, without creating an object every time, and the difference between a string and a

Source: Internet
Author: User

Core part reprinted from: http://www.cnblogs.com/springcsc/archive/2009/12/03/1616330.html

The StringBuffer class, like String, is also used to represent strings, except that because the StringBuffer is implemented in a different way than string, the StringBuffer does not generate a new object when string processing occurs. The memory usage is superior to the string class.

so in the actual use, if you often need to modify a string, such as inserting, deleting and so on, use StringBuffer to be more appropriate.

There are many methods in the StringBuffer class that are the same as the string class, which are functionally identical to the functions in the string class.

One of the most notable differences, however, is that each modification of a StringBuffer object alters the object itself, which is the biggest difference from the string class.

In addition, because StringBuffer is thread-safe , the concept of threading is followed by specific chapters, so it can be easily used in multithreaded programs, but the execution efficiency of the program will be slightly slower .

1. Initialization of StringBuffer objects

The initialization of the StringBuffer object is not the same as the initialization of the string class, Java provides special syntax, and typically is initialized with a constructor method.

For example:

(1), stringbuffer s = new StringBuffer (); This initializes the StringBuffer object as an empty object.

If you need to create a StringBuffer object with content, you can use:

(2),stringbuffer s = new StringBuffer ("abc");//This initializes the contents of the StringBuffer object as the string "abc".

It is important to note that StringBuffer and string are of different types and cannot be cast directly, and the following code is wrong :

StringBuffer s = "abc"; Assignment types do not match

StringBuffer s = (stringbuffer) "ABC"; There is no inheritance relationship and cannot be strongly turned

The code for the StringBuffer between the object and the string object is as follows:

String s = "abc";

StringBuffer sb1 = new StringBuffer ("123");

StringBuffer SB2 = new StringBuffer (s); Convert String to StringBuffer

String S1 = sb1.tostring (); StringBuffer Convert to String

2. Common methods of StringBuffer

The methods in the StringBuffer class mainly focus on changes to strings, such as Append, insert, and delete, which are the main differences between the StringBuffer and the string classes.

A, Append method

Public StringBuffer Append (Boolean B)

The function of this method is to append the content to the end of the current StringBuffer object, similar to a string connection. After the method is called, the contents of the StringBuffer object also change, for example:

StringBuffer sb = new StringBuffer ("abc");

Sb.append (TRUE);

The value of the object SB will become "Abctrue".

Using this method to concatenate strings will save more content than string, such as a connection applied to a database SQL statement, such as:

StringBuffer sb = new StringBuffer ();

String user = "Test";

String pwd = "123";

Sb.append ("select * from UserInfo where username=")

. Append (user)

. Append ("and pwd=")

. append (PWD);

The value of this object SB is the string "select * from UserInfo where username=test and pwd=123".

B, Deletecharat method

Public stringbuffer deletecharat (int index)

The function of this method is to delete the character at the specified position and then form the remaining content into a new string. For example:

StringBuffer sb = new StringBuffer ("Test");

SB. Deletecharat (1);

The function of the code is to delete the string object SB in the index value of 1 characters, that is, to delete the second character, the remaining content constitutes a new string. So the value of the object SB becomes "Tst".

There is also a function-like Delete method:

Public StringBuffer Delete (int start,int end)

The function of this method is to delete all characters within the specified interval, including the start, which does not contain the range of the end index value. For example:

StringBuffer sb = new StringBuffer ("teststring");

SB. Delete (1,4);

The purpose of the code is to remove all characters between the index value 1 (including) to the index value 4 (not included), and the remaining characters to form a new string. The value of the object SB is "Tstring".

C, insert method

Public stringbuffer Insert (int offset, Boolean b)

The function of this method is to insert content into the StringBuffer object and then form a new string. For example:

StringBuffer sb = new StringBuffer ("teststring");

Sb.insert (4,false);

The purpose of the sample code is to insert a false value at the index value 4 of the object SB, to form a new string, then the value of the object SB after execution is "testfalsestring".

D, Reverse method

Public StringBuffer Reverse ()

The function of this method is to invert the contents of the StringBuffer object and then form a new string. For example:

StringBuffer sb = new StringBuffer ("abc");

Sb.reverse ();

After the reversal, the content in the object SB becomes "CBA".

E, Setcharat method

public void Setcharat (int index, char ch)

The function of this method is to modify the character of the index value in the object to be the new character Ch. For example:

StringBuffer sb = new StringBuffer ("abc");

Sb.setcharat (1, ' D ');

The value of the object SB will become "ADc".

F, TrimToSize method

public void TrimToSize ()

The purpose of this method is to reduce the space waste by narrowing the storage space of the StringBuffer object to the same length as the string length.

In short, in the actual use, string and stringbuffer each have advantages and disadvantages, according to the specific use of the environment, select the corresponding type to use.

Two, StringBuffer and string differences:

Simply put, there is a relationship between a variable and a constant .

1, the contents of the StringBuffer object can be modified, and once the string object is created, it can not be modified, the re-assignment is actually two objects. (meaning that a new instance must be used when using a stringbuffer);

2, the internal implementation of StringBuffer and string, StringBuffer in string processing, do not generate a new object, in memory use is better than the string class.

So in the actual use, if you often need to modify a string, such as inserting, deleting and so on, use StringBuffer to be more appropriate.

String: There is no method in the string class to change a character in an existing string, because a single character in a Java string cannot be changed, so the object in the JDK document is called the String class immutable. However, an immutable string has a great advantage: The compiler can set the string to be shared.

The Stringbuffer:stringbuffer class belongs to an auxiliary class that can pre-allocate memory blocks of a specified length to create a string buffer. This uses the append method of the StringBuffer class to append the word transmitting string using the + operator to add characters to an already existing string that is much more efficient. Because using the + operator every time a character is added to a string, the string object needs to look for a new memory space to accommodate the larger string, which is a very time-consuming operation. Adding more than one character means re-allocating memory to the string again and again. This problem is avoided by using the StringBuffer class.

StringBuffer is thread-safe and can be easily used in multithreaded programs, but the execution of the program is relatively slow.

Look at the following code to implement the function:

Huawei Java Machine Test topic: Program Implementation goal: Enter a string, the corresponding ASCII value of each character plus 5, the output results. *

Program requirements: The string contains only lowercase letters, if the value of 5 after the character value is greater than ' Z ', convert it to a character starting from a.

1 /*2 * This program learns a few points3 * 1. The function to be called by the main function and the main function is set to static4 * 2, use of string directly, while StringBuffer must instantiate an object5 * 3, StringBuffer a few common methods:. append ();. toString ();6 * 4, string of several common methods:. CharAt (i);. length ();7  */8 9  Public classTest_java {Ten      Public Static voidMain (string[] args) { OneSystem.out.println (Change ("ABCD"))); A          -     } -      Public StaticString change (string mm) {//Note that it must be set to static, or the object will be generated to exist theStringBuffer nn =NewStringBuffer ();//Create an empty container -          for(intI=0;i<mm.length (); i++){ -             Chartmp; -TMP = (Char) (Mm.charat (i) +5);//the character of the first position +             if(Tmp> ' z '){ -Nn.append (' a ') ; +}Else{ A nn.append (TMP); at             } -         }         -         returnnn.tostring (); -          -     } -  in}

Java StringBuffer Class (reprinted) ____ Very important a class, thread-safe, without creating an object every time, and the difference between a string and a

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.