Java Basics--StringBuilder classes and StringBuffer classes for array applications

Source: Internet
Author: User

First, StringBuffer class

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 the StringBuffer is thread-safe , 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:

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:

StringBuffer s = new StringBuffer ("abc");

The content of this initialized StringBuffer object is 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 AppendMethod

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 DeletecharatMethod

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 InsertMethod

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 ReverseMethod

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 SetcharatMethod

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 TrimToSizeMethod

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.

StringBufferOverview

StringBuffer is a String buffer, which has the following characteristics:

1, it is a container. You can store any type of element (data).

2, it is multi-threaded security .

3, variable-length .

4, the content and the length of the deposit can be modified.

5, the container will usually have some basic methods, add, delete, modify, get. Curd =>create Update Read Delete

6, the string buffer will eventually be converted to string data for others to use.

StringBufferMethod

Increase:

stringbuffer Append(value);

stringbuffer Insert(index , value);

The difference between the append and insert methods:

The |--append method can only be appended at the tail.

The |--insert method can be added at any location.

sb.append ("a"): Append (9). Append (' a ') output is:a9a

Delete:

stringbuffer Delete(start,end);// when the value of end is greater than the maximum angle of the string, the end equals the maximum angle label

stringbuffer deletecharat(index);// Delete specified characters

Modify:

stringbufferreplace (start,end,str)// Replace string of specified length

void Setcharat(index,shar) // replace the character at the specified position

Get:

indexof// Get character location

Length ();// Get string Lengths

charAt ();// Gets the character of the specified corner mark

substring (start);// Gets the string from the specified position to the end

substring (start,end);// gets the string from the start-end-1 angle

stringbuffer setLength(0); Clears the buffer setLength (index) to set the length of the buffer.

sb. StringBuffer Delete (0,sb.length ()) empties the buffer

TwoStringBuilder class

There are three things to upgrade:

1. Improve efficiency

2. Simplified code

3. Improve safety

After JDK1.5 , there was StringBuilder, just to improve the efficiency.

StringBuilder is used on a single thread to improve efficiency. Because it is unlocked, it does not have the security of multithreading

StringBuilder inside has the lock, the single-threaded use each time needs to judge the lock, the efficiency is not high.

Three, the difference of String, StringBuffer, StringBuilder 1. Variable and immutable

  The string class uses a character array to hold strings, as follows, because there is a "final" modifier, so you know that the string object is immutable.

    private Final char value[];

  Both StringBuilder and StringBuffer inherit from the Abstractstringbuilder class, and in the Abstractstringbuilder, they are also used to hold strings in a character array, as follows, that both of these objects are mutable.

Char[] value;

2. Whether multithreaded security

The objects in string are immutable and can be understood as constants, apparently thread-safe .

Abstractstringbuilder is the common parent of StringBuilder and StringBuffer, and defines some basic operations for strings, such as expandcapacity, append, insert, indexof, and other public methods.

StringBuffer is thread-safe because it adds a synchronous lock to a method or a synchronous lock on a method that is called. See the following source code:

 Public synchronized StringBuffer Reverse () {    Super. Reverse ();     return  This ;}  Public int indexOf (String str) {    return indexOf (str, 0);        // There is a public synchronized int indexOf (String str, int fromIndex) method }

StringBuilder does not have a synchronous lock on the method, so it is non-thread safe .

3. StringBuilder and StringBuffer in common

StringBuilder and StringBuffer have public parent class Abstractstringbuilder ( abstract class ).

One of the differences between an abstract class and an interface is that the public methods of some subclasses can be defined in an abstract class, and subclasses only need to add new functionality, and do not need to repeat the existing methods, whereas interfaces are simply definitions of the declarations and constants of the methods.

StringBuilder, StringBuffer methods will call public methods in Abstractstringbuilder, such as Super.append (...). Just stringbuffer will add synchronized keywords to the method and synchronize.

Finally, if the program is not multithreaded, then using StringBuilder is more efficient than StringBuffer.

RELATED links:

Dark Horse Programmer _java Basics (StringBuffer and StringBuilder)

The difference between string, StringBuffer, StringBuilder in Java

Sorting out the differences between StringBuilder and StringBuffer two classes in Java

Explore string, StringBuilder, and StringBuffer in Java

10 questions about string types in Java

Deep understanding of Java:string

Methods and descriptions of string classes in Java

Java Basics--StringBuilder classes and StringBuffer classes for array applications

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.