Java String, StringBuffer and
StringBuilder
Sujit Kumar
Zenolocity LLC
Copyright @
Mutability
• String is immutable – cannot change once it
has been created.
• StringBuffer is mutable.
• StringBuilder is mutable.
Thread Safety
• StringBuffer is thread-safe => all methods are
synchronized.
• StringBuilder is NOT thread-safe.
• Slight performance overhead with using
StringBuffer class as compared to using the
StringBuilder class.
When to use each?
• Use String if you require immutability
• Use StringBuffer if you need mutability and
thread-safety.
• Use StringBuilder if you need mutability but
no thread-safety but better performance.

String, StringBuffer and StringBuilder

  • 1.
    Java String, StringBufferand StringBuilder Sujit Kumar Zenolocity LLC Copyright @
  • 2.
    Mutability • String isimmutable – cannot change once it has been created. • StringBuffer is mutable. • StringBuilder is mutable.
  • 3.
    Thread Safety • StringBufferis thread-safe => all methods are synchronized. • StringBuilder is NOT thread-safe. • Slight performance overhead with using StringBuffer class as compared to using the StringBuilder class.
  • 4.
    When to useeach? • Use String if you require immutability • Use StringBuffer if you need mutability and thread-safety. • Use StringBuilder if you need mutability but no thread-safety but better performance.