> For the complete documentation index, see [llms.txt](https://r24zeng.gitbook.io/leetcode-notebook/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://r24zeng.gitbook.io/leetcode-notebook/useful-java-knowledge/stringbuilder-vs-stringbuffer.md).

# StringBuilder vs StringBuffer

### Initialization

{% tabs %}
{% tab title="StringBuilder" %}

```java
// 在单线程更高效，但在多线程中不安全
everything is as same as StringBuffer
```

{% endtab %}

{% tab title="StringBuffer" %}

```java
// 在多线程更好，但不够高效，在多线程中更安全
// 加了lock功能，防止多线程同时修改某个string引起conflict
StringBuffer s = new StringBuffer();
// original capacity is 16, length is 0

StringBuffer s = new StringBuffer("abc");
/// current capactity is 16+3, length is 3

s.append("de")
// current capacity is 19, length is 3+2


```

{% endtab %}
{% endtabs %}

### Useful methods

{% tabs %}
{% tab title="StringBuilder" %}

```java
// Some code
```

{% endtab %}

{% tab title="StringBuffer" %}

```
s.append("ccd");   // s is updated


```

{% endtab %}
{% endtabs %}
