Back In the print window choose "Save as PDF" as the destination
NOTE.CS

String, StringBuilder and StringBuffer

1 topic · 28 Nov 2026
1

String, StringBuilder and StringBuffer ★★★★★

Java
StringStringBuilderStringBuffer
ImmutableMutableMutable
Thread-safe (because immutable)Not thread-safeThread-safe (synchronized)
Slow for many changesFastestSlower than StringBuilder
Java
String s1 = "hello";               // string pool
String s2 = "hello";               // same pool object
String s3 = new String("hello");   // new heap object
System.out.println(s1 == s2);      // true  (same reference)
System.out.println(s1 == s3);      // false
System.out.println(s1.equals(s3)); // true  (same content)

StringBuilder sb = new StringBuilder();
for (int i = 0; i < 5; i++) sb.append(i);
System.out.println(sb.reverse());  // 43210

Q & A

  1. == vs equals()?
    == compares references (same object?). equals() compares content. Always use equals() for strings.
  2. Why is String immutable?
    For security (class names, URLs, passwords), string pool sharing, thread safety and caching the hashCode.