Avatar ·

How to clear StringBuilder in Java: correct ways and pitfalls

Hello, colleagues! I'm a beginner Java developer and I've encountered this problem: in a loop I use StringBuilder to accumulate strings, and then I need to clear it before the next iteration. At first I tried to do this:\n\n```java\nStringBuilder sb = new StringBuilder("Hello");\nsb.append(" World");\nSystem.out.println(sb); // Hello World\n\n// Trying to clear\nsb = new StringBuilder();\n```\n\nBut this creates a new object, and the old one remains in memory — not very efficient. Then I came across the `delete()` method and tried:\n\n```java\nsb.delete(0, sb.length());\n```\n\nThis works, but I'm not sure it's the optimal way. I also saw somewhere the `setLength(0)` method, but I didn't understand how it works.\n\nIn general, the question is: how to properly and efficiently clear a StringBuilder? What are the ways?