StringBuffer in Java

Source: Internet
Author: User

Brief introduction:

both string and StringBuffer can store and manipulate strings, which are string data that contains multiple characters. Their difference is that the string class is a constant of strings and is immutable. While StringBuffer is a string variable, its objects can be expanded and modified. briefly, the main performance difference between the string type and the StringBuffer type is that the string is an immutable object, so each time a change is made to the string type it is equivalent to generating a new string object, and then the pointer Point to the new string object, so it is best not to use string to change the content of the strings, because each generation of objects will have an impact on the system performance, especially when there is no reference object in memory, the JVM's GC will start to work, the speed will be quite slow.

If you use the StringBuffer class, the result will be different, and each result will operate on the StringBuffer object itself, instead of generating a new object and changing the object reference. So in general we recommend the use of StringBuffer, especially if the string object is constantly changing. In some special cases, string object concatenation is actually interpreted by the JVM as a concatenation of StringBuffer objects, so the speed of a string object is not slower than the StringBuffer object, especially in the following string object generation, Stri NG efficiency is far faster than StringBuffer:
String S1 = "This was only a" + "simple" + "test";
StringBuffer Sb = new StringBuilder ("This was only a"). Append ("simple"). Append ("test");
You'll be surprised to find that the speed at which the String S1 object is generated is simply too fast, and at this point the stringbuffer is not at all dominant at all. In fact, this is a JVM trick, in the JVM's eyes, this
String S1 = "This was only a" + "simple" + "test"; is actually:
String S1 = "This was only a simple test"; So of course it doesn't take much time. But it is important to note that if your string is from another string object, the speed is not so fast, for example:
String S2 = "This was only a";
String S3 = "simple";
String S4 = "Test";
String S1 = S2 +s3 + S4;
At this point the JVM will behave in the same way as it did
.
StringBuffer
Java.lang.StringBuffer A variable sequence of characters for thread safety. A string-like buffer, but cannot be modified. Although it contains a specific sequence of characters at any point in time, some method calls can change the length and content of the sequence.
String buffers can be safely used with multiple threads. These methods can be synchronized if necessary, so all operations on any particular instance appear to occur in a serial order that is consistent with the sequence of method calls made by each thread involved.
The main operations on StringBuffer are the Append and insert methods, which can be overloaded to accept arbitrary types of data. Each method effectively converts the given data into a string, and then appends or inserts the character of the string into the string buffer. The Append method always adds these characters to the end of the buffer, while the Insert method adds characters at the specified point.
For example, if z refers to a string buffer object where the current content is "start", this method call Z.append ("le") causes the string buffer to contain "startle", and Z.insert (4, "le") will change the string buffer to contain " Starlet ".
Method:

constructor of the StringBuffer class: Public StringBuffer (): An object that creates an empty StringBuffer class.

public stringbuffer (int length): Creates an object of length StringBuffer class (Note: If the parameter is less than 0, the negativearraysizeexception exception is triggered.) )。

Public StringBuffer (String str) creates an object of the StringBuffer class with an existing string.

Method:

(1) StringBuffer append (type T): Appending a type of element to a string buffer t,t can be a Boolean, a character, a character array, a double, a floating-point number, an integer number, a string of type long integer, a string, and a StringBuffer class. If you add a string that exceeds the length of the string buffer, Java automatically expands.

(2) int capacity (): Returns the total space of the current StringBuffer object, not the length of the word a number.

(3) Char cahrat (int index): The character of index number in the current StringBuffer object. The first index is 0.

(4) stringbuffer Delete (int start, int end): Deletes the substring in the current StringBuffer object that begins with the index number start and ends at end.

(5) StringBuffer deletecharat (int index): Deletes the character with index number in the current StringBuffer object.

(6) void ensurecapacity (int minimumcapacity): Sets the total space of the word symbol string buffer. If the minimumcapacity is larger than the current total space, the new space is set: One result is minimumcapacity, and the other is {"Old space" multiplied by 2 plus 2}.

(7) void GetChars (int srcbegin, int srcend, char[] DST, int dstbegin): Starting with the index number StringBuffer of the current Srcbegin object, to the srcend end of the substring, Assign a value to the character array in DST, and start with the DST index number dstbegin.

(8) Int indexOf (String str): Returns the position of the current StringBuffer object, the first one that satisfies the STR substring.

(9) Int indexOf (String str, int fromIndex): Finds from the fromIndex of the current StringBuffer object and returns the position of the first one that satisfies the STR substring.

StringBuffer Insert (int offset, type T): These methods insert a type element T in the current StringBuffer object and insert T at the index number offset.

(one) int lastIndexOf (String str): Returns the last position in the current StringBuffer object that satisfies the STR substring.

int lastIndexOf (String str, int fromIndex): Finds from the fromIndex of the current StringBuffer object, returning the last position that satisfies the STR substring.

int length (): Returns the length of the string in the current StringBuffer object (character buffer). Note: This method differs from capacity ().

StringBuffer replace (int start, int end, string str): Replaces the string of the current StringBuffer object. From start, replace to Str where end ends.

(stringbuffer) reverse (): Flips the string.

(+) void Setcharat (int index, char ch): Sets the index number of the character to Ch.

(+) void setLength (int newlength): Sets the length of the string in the string buffer and, if newlength is less than the current string length, truncates the extra characters.

String substring (int start): Takes the substring from start to end in the current StringBuffer object.

String substring (int start, int end): Takes the substring from start to end in the current StringBuffer object.

() string toString (): Converts the current StringBuffer object to a String object.

Simple example: 

Public String toString ()convert to a String class object and return. Because most of the arguments for the displayed method in most classes are objects of the string class, it is often time to convert an object of the StringBuffer class to an object of the string class, and then display its value. Usage such as:stringbuffer sb=new StringBuffer ("How is You?");label L1=new label (Sb.tostring ());(Note: A Label object is declared on the L1,L1 content is how is it?)Public StringBuffer Append (boolean b)Public StringBuffer Append (char c)Public stringbuffer Append (int i)Public StringBuffer Append (long L)Public StringBuffer Append (float f)Public StringBuffer append (double D)The above 6 methods append a Boolean, char,int, long, float, and double 6 types of variables to the object of the StringBuffer class. Usage such as:double d=123.4567;stringbuffer sb=new stringbuffer ();Sb.append (true);sb.append (' C '). Append (D). append (in);(Note: SB's value is truec123.456799)Public stringbuffer Append (String str)appends the string constant str to the object of the StringBuffer class. Public stringbuffer Append (char str[])appends the character array str to the object of the StringBuffer class. Public StringBuffer Append(char str[], int offset, int len)appends the character Array str, starting at offset to the Len character, to the back of the object of the StringBuffer class. Public stringbuffer Insert (int offset, Boolean b)Public stringbuffer Insert (int offset, char c)Public stringbuffer Insert (int offset, int i)Public stringbuffer Insert (int offset, long l)Public stringbuffer Insert (int offset, float f)Public stringbuffer Insert (int offset, double d)Public stringbuffer Insert (int offset, String str)Public stringbuffer Insert (int offset, char str[])Inserts a Boolean, char, int, long, float, double-type variable, an object of the string class, or an array of characters into the offset position of the object in the StringBuffer class. Usage such as:stringbuffersb=new stringbuffer ("ABFG");Sb.insert (2, "CDE");(Note: SB's value is ABCDEFG)public int Length ()This method returns the length of a string variable, similar in usage to the string class's length method. stringbuffer sbf=new stringbuffer ();System.out.println (Sbf.capacity ());System.out.println (Sbf.length ());output of 0.The default constructor is automatically assigned capacity by the system and is 16 characters by default. Because there is no assignment, the length of the buffered object is 0.stringbuffer sbf=new stringbuffer (100); Set the size of the constructorthe CharAt () method can return a single character in a characterThe setcharat (0, ' x ') method can be used to replace a single character in a characterThe reverse () method can invert the string contents.

StringBuffer 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.