Java Strings: String, StringBuffer,
StringBuilder
All Methods with Examples
INTRODUCTION
Introduction to Strings
• • String: Immutable sequence of characters
• • StringBuffer: Mutable, thread-safe
(synchronized)
• • StringBuilder: Mutable, faster but not
synchronized
• • Strings are widely used in Java for text
manipulation
STRING CLASS
String Methods with Examples
• • length(): Returns string length
• Example: "Hello".length() → 5
• • charAt(): Returns character at index
• Example: "Java".charAt(2) → 'v'
• • substring(): Extracts substring
• Example: "Programming".substring(3,7) →
'gram'
STRINGBUFFER CLASS
StringBuffer Methods with
Examples
• • append(): Add string at end
• Example: new
StringBuffer("Hello").append(" World") →
'Hello World'
• • insert(): Insert at position
• Example: sb.insert(5, "Java")
• • delete(): Delete substring
STRINGBUILDER CLASS
StringBuilder Methods with
Examples
• • Same as StringBuffer methods
• • append(), insert(), delete(), reverse()
• • Faster performance (not synchronized)
• Example: new StringBuilder("Hi").append("
Java") → 'Hi Java'
Comparison: String vs StringBuffer
vs StringBuilder
• String → Immutable
• StringBuffer → Mutable, Thread-safe
• StringBuilder → Mutable, Faster, Not thread-
safe
• Use String when immutability is required.
• Use StringBuffer when working with threads.
• Use StringBuilder for single-threaded
performance.
Summary
• ✔ String is immutable
• ✔ StringBuffer is mutable & synchronized
• ✔ StringBuilder is mutable & faster
• ✔ Choose based on performance vs thread
safety