StringBuilder in Java — Java Technical Interview Questions & Answers

StringBuilder in Java

StringBuilder in Java

  • StringBuilder is a mutable text builder for one thread. append, insert, reverse. Not synchronized, so faster than StringBuffer. This is the default builder in fresher code.
  • new StringBuilder().append("Ja").append("va").toString() → "Java". Reverse a string with new StringBuilder(s).reverse().toString().
  • String itself stays immutable. Builder is only for when you change text many times.
  • Let's take this on the board with one tiny Main class — no extra files. StringBuilder in Java — output: Hi Java. append changes the same StringBuilder — not a new String each time. Start from main, go line by line, and stop at each print. That output is the proof for StringBuilder.

Technical Interview Tip: Default mutable builder. Show append or reverse(). Contrast Buffer = synced.

Code Examples for StringBuilder in Java

Example

// StringBuilder demo
public class Main {
  public static void main(String[] args) {
    StringBuilder sb = new StringBuilder("Hi");
    sb.append(" Java");
    System.out.println(sb.toString());
  }
}

StringBuilder in Java — output: Hi Java. append changes the same StringBuilder — not a new String each time.

How to Explain StringBuilder in Java to an Interviewer

StringBuilder vs StringBuffer?

Builder faster, not synced Buffer synced

How do you reverse a string?

new StringBuilder(s).reverse().toString()