Both StringBuilder
and StringBuffer
are used to mutate Strings. These classes also have the same methods so if you were to create a new StringBuffer or StringBuilder object you could use them interchangeably.
StringBuilder
1 | StringBuilder sb = new StringBuilder(); |
StringBuffer
1 | StringBuffer sb = new StringBuffer(); |
Both sb objects can now be used in the same manner and produce the same result.
Append to String
1 2 3 | sb.append("hello"); sb.append("world"); System.out.println(sb.toString()); |
Console Output
helloworld
Now if we want to insert a space between hello and world we can use our existing sb object and insert a space at index 5 which is the length of ‘hello’.
Insert into String
1 2 | sb.insert(5, " "); System.out.println(sb.toString()); |
Console Output
hello world
So should you use StringBuffer
or StringBuilder
? Generally you should choose StringBuilder
because it is faster and was created as a drop-in replacement for StringBuffer
.
That’s not all for StringBuffer
however, there is still a reason why you may want to use it. All of StringBuffer’s methods are synchronized so it is thread-safe and can be shared among threads.