> For the complete documentation index, see [llms.txt](https://comaqa.gitbook.io/java-automation/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://comaqa.gitbook.io/java-automation/oop-v-java/stringbuffer.md).

# StringBuffer

Как мы уже рассмотрели, строка String является некой константой, и каждый раз вы просто заново создаете некую новую константу и кладете ее в свою переменную, таким образом следует понимать, что любое изменение в строках связано с использованием памяти под новую строку.

```
String s = "a";
for(int i = 0; i < 100; i++)
{
       s+='a';
}
```

Сей прекрасный код создаст 100 строк, которые будут хранится в памяти, пока сборщик мусора не удалит их. Поэтому, если вы напишите такой код в реальном проекте, то вам оторвут руки. Чтобы редактировать строки следует использовать класс обертку StringBuffer.

```
StringBuffer s = new StringBuffer("a");
for(int i = 0; i < 100;i++)   {
      s.append('a');
}
```

Конструктор StringBuffer может принимать на вход строку, с которой можно проводить дальнейшие манипуляции. Кроме методов, которые позволяют добавить в конец строки различные типы данных (append), он также умеет удалять и вставлять символы в строки:

```
s.deleteCharAt(i);//удаляет символ в позиции i
s.delete(i, j);//удаляет подстроку с i - го по j - ый символ
s.insert(i,j);//вставляет на i - ое место объект j
```

Для того, чтобы вернутся от StringBuffer к String необходимо вызвать метод toString();

```
StringBuffer s = new StringBuffer("abcd");
 s.append('e');//abcde
 s.delete(1,2);//acde
 s.insert(1,'b');//abcde
 s.deleteCharAt(2);//abde
 String ans = s.toString();
```

Вопрос 1

```
На чём сказывается излишнее выделение памяти под переменные?
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://comaqa.gitbook.io/java-automation/oop-v-java/stringbuffer.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
