How can I clear or empty a StringBuilder?

To clear or empty a StringBuilder in Java, you can use the setLength method and set the length to 0. This will remove all characters from the StringBuilder and reset its length to 0. Here's an example of how to use the setLength method to clear a StringBuilder:

StringBuilder sb = new StringBuilder("Hello");
sb.setLength(0);  // clear the StringBuilder
System.out.println(sb.length());  // output: 0

You can also use the delete method to delete a range of characters from the StringBuilder. For example, to delete all characters from the StringBuilder, you can use the following code:

sb.delete(0, sb.length());

This will delete all characters from the StringBuilder, effectively clearing it.

Alternatively, you can create a new instance of StringBuilder to replace the existing one. This will create a new, empty StringBuilder that you can use in place of the old one.

sb = new StringBuilder();

Either way, this will clear the StringBuilder and allow you to start building a new string.