Programming Tips - Java: How to set the content of StringBuilder

Date: 2019mar8 Update: 2025oct14 Language: Java Q. Java: How to set the content of StringBuilder A. There isn't a method for this but there are two ways to do it. Full example:
class Demo { public static final void main(String[] args) { // Make it and set some content StringBuilder sb = new StringBuilder("Hello "); sb.append("World"); System.out.println(" first=" + sb); // Change all content in the StringBuilder by new-ing sb = new StringBuilder("Totally new content"); System.out.println("second=" + sb); // Another way, which is probably more efficient sb.replace(0, sb.length(), "The third content"); System.out.println(" third=" + sb); } }
Output:
first=Hello World second=Totally new content third=The third content