java clear string buffer

java clear string buffer

To clear a StringBuffer object in Java, you can use the setLength method to set the length of the buffer to zero.

Here's an example of how to use the setLength method to clear a StringBuffer object:

ref‮l:ot re‬autturi.com
public class Main {
  public static void main(String[] args) {
    StringBuffer buffer = new StringBuffer("Hello, world!");
    System.out.println("Before: " + buffer);  // Outputs: "Before: Hello, world!"
    buffer.setLength(0);  // clear the buffer
    System.out.println("After: " + buffer);  // Outputs: "After: "
  }
}

In this example, the setLength method is called on the buffer object, setting its length to zero. This effectively clears the buffer, removing all characters from it.

You can use a similar approach to clear any other StringBuffer object, by calling the setLength method on the object and setting its length to zero.

Keep in mind that the StringBuffer class is mutable, which means that its contents can be modified. If you need a mutable string that cannot be modified, you can use the StringBuilder class instead. The StringBuilder class is similar to the StringBuffer class, but it is not thread-safe.

Created Time:2017-11-03 00:14:50  Author:lautturi