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 oneWhy 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
| Method | What it does | Complexity |
|---|---|---|
length() | String length | O(1) |
charAt(i) | Character at index | O(1) |
substring(b, e) | Substring | Java 7+ O(n) |
indexOf(ch) | Find character | O(n) |
split(regex) | Split | O(n) (regex!) |
replace(a, b) | Replace chars | O(n) |
trim() | Remove spaces (ASCII only) | O(n) |
strip() | Java 11+ Unicode spaces | O(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 dotDate/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/23Enums
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, notjava.util.Date.
Enums are type-safe constants with superpowers.