Skip to content

Metadata Card

  • Difficulty: (Novice Village 2-star)
  • Prerequisites: Ch8 (OOP)
  • Core concepts: 5 (String immutability, StringBuilder, common methods, regex, utility classes)
  • Estimated time: 3-4 hrs
  • Languages: Java (primary) + Python/C++ (comparison)

The Breakthrough · Tracing the Origins

You've been using String s = "hello" + "world". Every concatenation creates a new object. 100 concatenations = 100 temporary strings. Strings are one of the biggest memory black holes in programming.

String Immutability

java
String s = "Hello";
s = s + " World"; // Creates a NEW String object, doesn't modify the old one

Why immutable?

  • Thread safety
  • String pool (literal reuse)
  • hashCode caching
  • Security (class loaders, network connections)

StringBuilder — Correct Concatenation

java
// WRONG — creates 100,000 temporary objects
String result = "";
for (int i = 0; i < 100_000; i++) {
 result += "line " + i + "\n"; // O(n²)!
}

// CORRECT
StringBuilder sb = new StringBuilder(1_000_000);
for (int i = 0; i < 100_000; i++) {
 sb.append("line ").append(i).append("\n");
}
String result = sb.toString();

Common Methods

MethodWhat it doesComplexity
length()String lengthO(1)
charAt(i)Character at indexO(1)
substring(b, e)SubstringJava 7+ O(n)
indexOf(ch)Find characterO(n)
split(regex)SplitO(n) (regex!)
replace(a, b)Replace charsO(n)
trim()Remove spaces (ASCII only)O(n)
strip()Java 11+ Unicode spacesO(n)

Regex Basics

java
// NEVER do this:
"192.168.1.1".split("."); // Empty array! . is a regex wildcard

// Correct:
"192.168.1.1".split("\\."); // Escape the dot

Date/Time API (Java 8+)

java
// Old way — DON'T use
Date now = new Date();
now.getMonth(); // 0-based! Confusing.

// Modern way
LocalDate today = LocalDate.now();
LocalDate tomorrow = today.plusDays(1);
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy/MM/dd");
System.out.println(today.format(fmt)); // 2026/06/23

Enums

java
public enum Status {
 PENDING, ACTIVE, BANNED
}

// Type-safe — cannot pass arbitrary ints
void setStatus(Status status) { ... }

Final Challenge: Write a log analyzer that counts URL access frequency from 100K log lines, grouping by route and outputting top 10.

Traveler's Notes

String is immutable — every "change" creates a new object.
Use StringBuilder for loop concatenation.
Always specify encoding explicitly. Don't use FileReader's default charset.
Regex: . means "any character" — escape it!
Use Java 8 date/time API, not java.util.Date.
Enums are type-safe constants with superpowers.

Built with VitePress | Software Systems Atlas