Java's StringBuffer class

Source: Internet
Author: User

1.StringBuffer class overview

StringBuffer class overview: If you stitch a string, each stitch will build a new string object that is time consuming and wasteful. And stringbuffer can solve this problem.

A variable sequence of characters for thread safety.


2. Thread First Knowledge

Thread safety is the synchronization between threads. For example: Today I took my bank card to the ATM to withdraw money, but at the same moment my wife took the passbook to the bank to get the money. It is very happy if the data between the banking systems is out of sync or if the threads are unsynchronized. I took 1000 yuan at the teller machine, and my wife took the passbook at the bank and took 1000 yuan. Well, that kind of thing is very "scary". So, thread safety is the synchronization between threads, which means the security of the data.


In the same way, threads are unsafe, which is a step out of sync between threads. For example, while watching TV, I can chat with others. Therefore, the thread is not safe, that is, the thread is not synchronized, but the different steps also have the advantage Ah, that is high efficiency. In other words, if the thread is safe, I watch TV first, then watching TV, and then talking to others, so that I can seriously watch TV, but others may have been in the mood to chat at this point in time.


So, thread-safe, that is, synchronization between threads. and thread insecurity, that is, the different steps between threads, is the problem that always bothers us. It depends on how we think, if you want data security, then thread-safe, that is, synchronization between threads, and conversely, if you are pursuing efficiency, then it is unsafe to thread, that is, the threads are out of sync.


There are many examples of thread safety in life, such as hospital sites and banks ' websites. But there are many examples of thread insecurity, such as news sites, forums, and so on.


What is the difference between 3.StringBuffer and string?

The length and content of the former are variable, and the latter is immutable.

If you use the former to do string concatenation, you will not waste too much resources.


4. Construction method

Public StringBuffer ()

Public StringBuffer (charsequence seq)

public stringbuffer (int capacity)

Public StringBuffer (String str)

Construction method of Package cn;/** * stringbuffer  * public stringbuffer ()   Non-parametric construction method  *  public stringbuffer (int capacity)   Specifies the capacity of the string buffer object  * public stirngbuffer ( STRING STR)   Methods for specifying string contents of string buffer objects  * * stringbuffer  * public int  Capacity ()   return current capacity  * public int length ()   return length   */public class  stringbufferdemo {public static void main (String[] args)  {//public  StringBuffer ()   Non-parametric construction method Stringbuffer sb = new stringbuffer (); System.out.println ("SB:" +SB);//sb:system.out.println ("SB's Length:" +sb.length ());//SB Length: 0system.out.println ("SB's Capacity: "+sb.capacity ());//SB Capacity: 16//public stringbuffer (int capacity)   String buffer object with specified capacity stringbuffer  Sb2 = new stringbuffer (50); System.out.println ("SB2:" +SB2);//sb2:system.out.println ("Length of SB2:" +sb2.length ());//SB2 Length: 0system.out.println (" Capacity of SB2: "+SB2.Capacity ());//SB2 Capacity: 50//public stirngbuffer (STRING STR)   String Buffer object specifying string contents STRINGBUFFER SB3  = new stringbuffer ("HelloWorld"); System.out.println ("SB3:" +SB3);//sb3:helloworldsystem.out.println ("Length of SB3:" +sb3.length ());// Length of SB3:10system.out.println ("SB3 Capacity:" +sb3.capacity ());//SB3 capacity: 26}}


5.StringBuffer Add, delete, replace, invert function

StringBuffer function of the class

package com;/** * stringbuffer Add function:  * public  stringbuffer append (STRING STR): You can add any type of data to the string buffer inside the  , and return the string buffer itself  * public  stringbuffer insert (INT OFFSET,STRING STR): You can add any type of data to the specified string buffer and return the string buffer itself  */ Public class stringbufferdemo2 {public static void main (String[] args)  {//Create a string buffer object Stringbuffer sb = new stringbuffer ();//public stringbuffer  Append (STRING STR): Can add any type to the string buffer inside the  stringbuffer sb2 = sb.append ("Hello"); System.out.println ("SB:" +SB),//sb:hellosystem.out.println ("SB2:" +SB2);//sb2:hellosystem.out.println (sb ==  SB2);//true//append () method can be called multiple times, chained programming System.out.println (Sb.append ("World"). Append (True). Append (' a '). Append ( false));//helloworldtrueafalsesystem.out.println (Sb.insert (0,  "Invincible"));//Invincible Helloworldtrueafalse}} 

StringBuffer class Delete function

Package com;/** * stringbuffer removal function  * public stringbuffer deletecharat (int  index)   Deletes the character at the specified position and returns the string buffer itself  * public stringbuffer delete (int strat,int  end)   Deletes the content from the specified position to the end of the specified position and returns the string buffer itself  * */public class stringbufferdemo3 { Public static void main (String[] args)  {//Create object Stringbuffer sb = new  stringbuffer (); Sb.append ("HelloWorld"). Append ("Java"); System.out.println (SB);//helloworldjava//public stringbuffer deletecharat (Int index)   Deletes the character at the specified position and returns the string buffer itself//requirements: Ask to delete the E character, what should I do? System.out.println (Sb.deletecharat (1));//hlloworldjava//requirements: I want to delete the first L character, what should I do? System.out.println (Sb.deletecharat (1));//hloworldjava//public stringbuffer delete (Int strat,int  end)   Delete the content from the specified position to the end of the specified position and return the string buffer itself//requirements: I want to delete worldSystem.out.println (Sb.delete (3, 8));// hlojava//requirements: I want to delete all data System.out.println (Sb.delete (0, sb.length ()));/}} 

StringBuffer class substitution function

Package com;/** * StringBuffer Replacement function * Public stringbuffer replace (int start,int end,string str) Replace Strat C with str from */public to end Lass Stringbufferdemo {public static void main (string[] args) {//Create a string buffer object StringBuffer SB = new StringBuffer ();//Add Data sb. Append ("Hello"). Append ("World"). Append ("Java"); System.out.println ("Pre-replace:" +SB);//replace before: helloworldjava//public stringbuffer replace (int start,int end,string str) From Strat to end with STR replacement//demand: The World this data with "Happy Holiday" to replace Sb.replace (5, 10, "Happy Holidays"); System.out.println ("Replaced by:" +SB);//After replacement: Hello holiday happy Java}}

Reversal function of StringBuffer class

Package com;/** * StringBuffer class inversion function * public stringbuffer reverse () * */public class StringBufferDemo4 {public static voi D main (string[] args) {//define a string buffer object StringBuffer SB = new StringBuffer ();//Add Object Sb.append ("Push silly Breeze"); System.out.println ("Reverse Before:" +SB);//reverse before: Force silly Yang Breeze System.out.println ("after reversal:" +sb.reverse ());//Reverse: Wind Qing, stupid)

interception function of StringBuffer class

Package com;/** * StringBuffer class interception function * public string substring (int start) * public string substring (int start,int end) * */public class StringDemo6 {public static void main (string[] args) {//define a string buffer object StringBuffer SB = new StringBuffer (); Add Object Sb.append ("Hello"). Append ("World"). Append ("Java"); System.out.println ("The SB before intercept is:" +SB);//The Before intercept is: helloworldjava//intercept function//public string substring (int start) string s = Sb.substring (5); System.out.println ("s:" +s);//s:worldjavasystem.out.println ("The SB after interception is:" +SB);//SB after interception: Helloworldjava}}


Conversion of 6.StringBuffer and string classes to each other

Package cn;/** *  string and StringBuffer-class conversions?  *  string-->stringbuffer Conversion: We convert Class A to class B, actually to use the function of B.  *  stringbuffer-->string conversion: The result we may want is a string type, so we have to go back  */public class  Stringdemo7 {public static void main (String[] args)  {String s =  " Hello ";//cannot assign the value of the string directly to STRINGBUFFER//1. By constructing method Stringbuffer sb = new stringbuffer (s); System.out.println ("String-->stringbuffer:" +SB);//string-->stringbuffer:hello//2. by append () method Stringbuffer sb2 = new stringbuffer (); Sb2.append (s); System.out.println ("String-->stringbuffer:" +SB2);//string-->stringbuffer:hello//stringbuffer-->string 1. Through the ToString () method Stringbuffer buffer = new stringbuffer ("Java"); String str = buffer.tostring (); System.out.println ("stringbuffer-->string:" +str);//stringbuffer-->string:java//2. How to construct strings by string  str2 = new sTring (buffer); System.out.println ("stringbuffer-->string:" +STR2);//stringbuffer-->string:java}}


7. Stitch the array into a string

package cn;/** *  stitching arrays into a string   * */public class StringBufferTest2  {Public static void main (String[] args)  {//defines an array int[] arr = new  int[]{44,33,66,33,22};//method One: Low efficiency//Definition function string str = arraytostring (arr);// After stitching the string System.out.println ("stitched string:" +str);//String after stitching: [44, 33, 66, 33, 22]// Method Two: Use StringBuffer. Such efficiencies are high string str2 = arraytostring2 (arr); System.out.println ("Stitched string:" +str2);//String after stitching: [44, 33, 66, 33, 22]}public static  string arraytostring2 (Int[] arr) {stringbuffer sb = new stringbuffer (); Sb.append ("[");for  (int i = 0; i < arr.length; i++)  {if (i  == arr.length -1) {sb.append (arr[i]);} Else{sb.append (Arr[i]). Append (", ");}} Sb.append ("]"); return sb.tostring ();} Public static string arraytostring (Int[] arr) {STRING&Nbsp;s =  "";s +=  "[";for  (int i = 0; i < arr.length;  i++)  {if (i == arr.length -1) {s += arr[i];} else{s += arr[i]+ ", ";}} s +=  "]"; return s;}}


8. String inversion

Package cn;public class stringbuffertest3 {public static void main (String[]  args)  {String s =  "I love You";//Call Method one System.out.println (reverse (s));//You Love Me// Call Method Two System.out.println (Reverse1 (s));//You love me//But calling method one and method two   means producing a lot of "rubbish", so inefficient, in order to improve efficiency, We can first convert the string to stringbuffer,//and then call StringBuffer's reverse () method, and finally convert StringBuffer to System.out.println (Reverse2 (s)). ;//You Love Me}/** *  method one: Use the length () and Charat () method of string  *  @param  s *  @return  */ Public static string reverse (string s) {string str =  "";for  (int i  = s.length () -1; i >= 0; i--)  {str += s.charat (i);  } Return str;} /** *  method Two: First convert a string to a character array by ToCharArray () and then invert the character array  *  @param  s *  @return  * /public static string reverse1 (string s) {Char[] chs = s.tochararray ();   (Int i = chs.lengTh -1,j=0; i > j; i--, J + +)  {char temp = chs[i];chs[i] =  chs[j];chs[j] = temp;} Return  new string (CHS);} /** *  method Three: We can first convert the string to stringbuffer *  and then call StringBuffer's reverse () method, and then convert the StringBuffer.  *  @param  s *  @return  */public static string reverse2 (String  s) {Return new stringbuffer (s). Reverse (). ToString ();}}


9. Determine if a string is a symmetric string

package cn;/** *  *  requirements: Determine if a string is symmetric   string  * */public class  Stringbuffertest4 {public static void main (String[] args)  {String str  =  "ABC"; string str1 =  "ABBA"; string str2 =  "ABA";//Call Method One: System.out.println (Issame (str));//falsesystem.out.println (Issame ( STR1)//truesystem.out.println (Issame (str2));//true//Call method Two: System.out.println (isSame2 (str));// FalseSystem.out.println (IsSame2 (str1));//truesystem.out.println (IsSame2 (str2));//true}/** *  Method One: First convert the string to a character array, and then judge the end of the array of characters  *  @param  s *  @return  */public static  Boolean issame (string s) {Char[] chs = s.tochararray ();for  (int i =  0,j=chs.length-1; i < j; i++,j--)  {if (Chs[i] != chs[j]) {return  false;}} Return true;} /** *  method Two: By converting a string to StringBuffer, then inverting it, then converting it to string, and then the original String comparison  *  @param  s *  @return  */public static boolean issame2 (String  s) {Return new stringbuffer (s). Reverse (). ToString (). Equals (s);}}


What is the difference between 10.String, StringBuffer and StringBuilder?

A string is a content that cannot be changed, while StringBuffer and StringBuilder are content mutable.

StringBuffer is data synchronization, is thread-safe, inefficient, and StringBuilder is data is not synchronized, thread insecure, high efficiency.


What is the difference between 11.StringBuffer and arrays?

Both can be seen as a container, loaded with other arrays.

The StringBuffer array is ultimately a string of data.

Arrays can be placed in multiple arrays, but must be of the same data type.


This article is from the "11831428" blog, please be sure to keep this source http://11841428.blog.51cto.com/11831428/1860211

Java's StringBuffer class

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.