Get the App
SLTechnology News&Howtos  ›  Development  › 

What is the difference between StringBuffer and StringBuilder in JAVA

Shulou Source: shulou.com Published: 2022-06-03 16:28:07 09月18日 Update

This article mainly explains "what is the difference between StringBuffer and StringBuilder in JAVA". The explanation in this article is simple and clear, easy to learn and understand. Please follow the ideas of Xiaobian slowly and deeply to study and learn "what is the difference between StringBuffer and StringBuilder in JAVA" together!

inheritance relationship

Look at the inheritance structure of StringBuffer and StringBuilder classes from the source code:

StringBuffer and StringBuilder inherit from AbstractStringBuilder class.

How to achieve expansion

StringBuffer and StringBuilder expansion mechanism is implemented in the abstract class AbstractStringBuilder, when the length is found to be insufficient (default length is 16), it will automatically expand the work, expand to the original array length of 2 times 2, create a new array, and copy the array data to the new array.

public void ensureCapacity(int minimumCapacity) { if (minimumCapacity > 0) ensureCapacityInternal(minimumCapacity);} /** * Make sure that the value character array does not cross boundaries. new an array with a reference to value*/ private void ensureCapacityInternal(int minimumCapacity) { // overflow-conscious code if (minimumCapacity - value.length > 0) { value = Arrays.copyOf(value, newCapacity(minimumCapacity)); }} /** * Capacity expansion: expand the length to 2 times the previous size +2*/ private int newCapacity(int minCapacity) { // overflow-conscious code expand 2 times +2 //here may overflow, overflow is negative ha, note int newCapacity = (value.length

Tags: Thread security array length character method efficiency source code insufficient string security data time mechanism learning testing code key keyword content Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Technology Shulou Information Huawei macOS Docker