String vs StringBuilder vs StringBuffer
45 min · Beginner
String is immutable, while StringBuilder and StringBuffer are mutable text buffers you change in place. Knowing which to use, and why + in a loop is slow, is one of the most common core Java questions.
Topics in this lesson
- Comparison: mutability, thread safety and speed
- Why + in a loop is slow
- Methods interviewers ask about
- Coding question: reverse and palindrome
- Trap: StringBuilder does not override equals
Interview questions this lesson answers
- What is the difference between String, StringBuilder and StringBuffer?
- What is a mutable object?
- When was StringBuilder added, and why?
- Which should you use by default for building strings?
- Why is
+inside a loop slow? - Does the compiler optimise
+? - Is StringBuilder thread-safe?
- Is StringBuffer always safe in multithreaded code?
- What is the default capacity of a StringBuilder?
- What is the difference between length and capacity?
Sign in free to continue this lesson
Create a free account to read every lesson, practise with the exercises and keep track of your progress.