Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

What is the difference between Sring and StringBuffer and StringBuilder in Java?


May 28, 2021 Article blog


Table of contents


A lot of people know about Java String, Stringbuffer, and StringBuilder, so do you know what the difference is?

Variability

String classes typically use an array of characters to hold strings, such as Private, final, char, and value, so we say that string objects are immutable.

Both Stringbuffer and StringBuider are inherited from the AbstractStringBuilder class, and in AbstractStringBuilder, an array of characters is also used to save the string, char , value, both of which are variable.

performance

When you change the String type, a new String object is generated, followed by a target for the new String object. S tringBuffer manipulates the StringBuffer object itself instead of generating a new object and changing the object's reference. In the same case, stringBuffer can only get a 10% to 15% performance gain with StringBuilder, and you run the risk that multiple threads are not safe.

Thread security

The objects in String are immutable, and that's all that the small editor brings you about Linux's common commands. s olution as constant, thread-safe. A bstractStringBuilder, as the public parent class of StringBuilder and StringBuffer, defines the basic operations of related strings, such as public methods such as expandCapacity, append, insert, indexOf, and so on. S tringBuffer adds a synchronization lock to the method or a sync lock to the called method, so the thread is safe. StringBuilder does not have a synchronization lock on the method, so it is not thread-safe.

A summary of all three

String: To manipulate a small amount of data

StringBuilder: Single-threaded operation of string buffers and manipulation of large amounts of data

StringBuffer: Multithreaded operation of string buffers and manipulation of large amounts of data

What's the difference between Sring and StringBuffer and StringBuilder in Java? the whole content.