Home > Java > javaTutorial > body text

Introduction to String, StringBuffer and StringBulider

零下一度
Release: 2017-06-23 09:32:29
Original
1417 people have browsed it

All three implement the CharSequence interface, so CharSequence can be considered as a string protocol interface

1. The String class is an immutable class, that is, once a String object is created, the content contained in this object The character sequence in is immutable until the object is destroyed;

When we often define String str=new String("defined me");

str="changed I";

The output has changed. It seems that Str has changed. In fact, the point of str has been changed. The original object in the heap memory has become garbage

2.StringBuffer class

StringBuffer represents a string with a variable character sequence. After a StringBuffer is created, the string can be changed through the insert(), append(), reverse(), serChaAt(), and setLength() methods. Finally, After generation, it can be converted into a String object through the toString() method

3. StringBuilder is new in JDK1.5 and also represents a string object. It is similar to StringBuffer. The constructors and methods of the two classes are also Basically the same, StringBuffer was thread-safe at that time, and StringBulider did not implement thread safety, so the performance was slightly higher. Therefore, if you create a string object with variable characters, you should give priority to the StringBuilder class

Comparison

1. The three have the following relationship in terms of execution speed:
StringBuilder>StringBuffer> String;

2.: First, the length is expandable; second, StringBuffer is thread-safe, and StringBuilder is thread-unsafe. So how are their lengths dynamically expanded and how is the thread safety of StringBuffer implemented?

All three implement the CharSequence interface, so CharSequence can be considered as a string protocol interface

All methods in StringBuffer except the construction method Limited by synchronized

The two extendable lengths are verified by ensureCapacity(int minimumCapacity) to verify whether the current length is less than the parameter minimumCapacity. If true, space is allocated. The step size for allocating new space is twice (current length + 1).

The above is the detailed content of Introduction to String, StringBuffer and StringBulider. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!