The difference between string class and StringBuffer class in Java

There are two string operations in Java: String class and StringBuffer class (buffer string processing class). Let's briefly talk about the differences between the two. String class and StringBuffer class provide corresponding methods to realize string operation, but they are slightly different.

(1) String class once this class generates a string, its object is immutable. The content and length of string class are fixed. If the program needs to obtain string information, it needs to call various string operation methods provided by the system. Although the string can be operated through various system methods, this does not change the object instance itself, but generates a new string Examples of. The system allocates memory for string objects according to the actual number of characters contained in the object.

(2) The StringBuffer class looks up the word buffer, which means buffering. This class must have buffering function. This class handles variable strings. If you want to modify the string of a StringBuffer class, you do not need to create a new string object, but directly operate the original string. Various string operation methods of this class are different from those provided by the string class. The system When allocating memory for the StringBuffer class, in addition to the space occupied by the current character, another 16 character buffer is provided. Each StringBuffer object has a certain buffer capacity. When the string size does not exceed the capacity, no new capacity will be allocated. When the string size exceeds the capacity, the capacity will be automatically increased.

Here are some specific examples

String connection

The string class has two methods

First ("+")

The second ("concat")

Method of StringBuffer class

The final output results are: add special effects! Duang~~

It is not difficult to see from the above example that when extending a string class, it needs to instance two objects, each of which will occupy a certain amount of memory, while the StringBuffer class does not need to instantiate a new class, but only needs to call an extended method.

Also, the memory capacity of the StringBuffer class is scalable. For example:

The capacity () method represents the number of string objects that can hold strings in memory. If you want to expand the memory capacity, you can use the method ensurecapacity().

The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support programming tips.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>