How do you clear the string buffer in Java after a loop so the next iteration uses a clear string buffer?
How do you clear the string buffer in Java after a loop so the next iteration uses a clear string buffer?
One option is to use the delete method as follows:
StringBuffer sb = new StringBuffer();
for (int n = 0; n < 10; n++) {
sb.append("a");
// This will clear the buffer
sb.delete(0, sb.length());
}
Another option (bit cleaner) uses setLength(int len):
sb.setLength(0);
See Javadoc for more info:
public void clear(StringBuilder s) {
s.setLength(0);
}
Usage:
StringBuilder v = new StringBuilder();
clear(v);
for readability, I think this is the best solution.
I suggest creating a new StringBuffer (or even better, StringBuilder) for each iteration. The performance difference is really negligible, but your code will be shorter and simpler.
I used this below code to store password for temporary processing like regex matching and clear it once done. The usual delete method does not reset all the characters, which was not suitable for me. This code satisfied my requirement.
public static void clear(StringBuilder value) {
for (int i = 0, len = value.length(); i < len; i++) {
value.setCharAt(i, Character.MIN_VALUE);
}
value.setLength(0);
}
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("clear this password");
// use & process sb
clear(sb);
}
I think the best way to clear StringBuilder is Clear() method.
StringBuilder sb = new StringBuilder();
sb.Clear();