Analysis of common usage methods of StringBuffer in Java
StringBuffer
When modifying strings, you need to use StringBuffer and StringBuilder classes. Unlike the string class, the objects of the StringBuffer and StringBuilder classes can be modified multiple times without generating new unused objects. The StringBuilder class is proposed in Java 5. The biggest difference between it and StringBuffer is that the StringBuilder method is not thread safe (cannot be accessed synchronously).
Because StringBuilder has a speed advantage over StringBuffer, it is recommended to use StringBuilder class in most cases. However, when the application requires thread safety, the StringBuffer class must be used
Once the content of the string is created, it is not allowed to change. If it is changed, a new string object will be created.
Generally, the content of the string will not be modified at will, because each modification will create a new string object.
If you need to modify the contents of the string: it is recommended to use the string buffer class.
StringBuffer (string buffer class): a collection container that stores characters.
Written test question: what is the default initialization capacity of the StringBuffer parameterless construction method? How much will it automatically increase when the capacity is insufficient?
The bottom layer of StringBuffer maintains a character array. When storing characters, they are actually stored in the character array,
The initialization capacity of the character array is 16. When the capacity is not enough, it will automatically double.
Common methods of StringBuffer:
increase
StringBuffer ("Jack") is assigned when creating objects
Append() adds a new text object at the end of the buffer
Insert() adds a new text object at the specified subscript position
Delete
delete(int start,int end)
deleteCharAt(int index)
check
Tostring() returns the string of this container
Indexof (string STR) returns the index of the first occurrence of the specified substring in the string.
Substring (int start) intercepts the string from the beginning
change
Replace (int start int endstring STR) replaces the characters in the substring of this sequence with the characters in the given string. The substring starts at the specified start and ends at the index end - 1
Setcharat (int index char CH) specifies the index position to replace one character
When is the string buffer class used?
If the content of a string needs to be modified frequently, we need to use the string buffer class.
summary
The above is all about the analysis of common usage methods of Java StringBuffer in this article. I hope it will be helpful to you.