Working with Strings
1. Creating Strings
| Form | Example |
| Literal | String s = "hello"; |
| Constructor | new String("hi") (avoid) |
| From char[] | new String(chars) |
| From bytes | new String(bytes, StandardCharsets.UTF_8) |
| Text block | """multi\nline""" |
2. Understanding String Immutability
| Aspect | Detail |
| Class | final class String |
| Mutating method? | None — all methods return NEW String |
| Benefit | Thread-safe, hashable, cacheable, secure |
3. Understanding String Pool
| Item | Detail |
| Location | Heap (since Java 7) |
| Literal | Auto-interned |
new String("x") | Allocates new object outside pool |
s.intern() | Returns canonical pool reference |
4. Concatenating Strings
| Method | Use |
+ operator | Compiles to StringBuilder (Java 9+ uses invokedynamic) |
String.concat(s) | Single concat |
String.join(delim, parts) | With separator |
StringBuilder | Loops/many concats |
"%s".formatted(x) | Templated |
5. Comparing Strings
| Method | Use |
a.equals(b) | Value equality |
a.equalsIgnoreCase(b) | Case-insensitive |
a.compareTo(b) | Lexicographic, <0 / 0 / >0 |
a.compareToIgnoreCase(b) | Case-insensitive ordering |
a == b | Reference identity — avoid |
| Null-safe | Objects.equals(a, b) |
| Method | Description |
substring(start) | From index to end |
substring(start, end) | End exclusive |
charAt(i) | Single char |
chars() | IntStream of code points |
codePoints() | Unicode-aware stream |
7. Searching Strings
| Method | Returns |
contains(seq) | boolean |
indexOf(s) / lastIndexOf(s) | int (-1 if absent) |
startsWith(p) / endsWith(p) | boolean |
matches(regex) | Full match |
8. Modifying Strings
| Method | Result |
replace(c, c) | Replace all chars |
replace(seq, seq) | Literal replacement |
replaceAll(regex, repl) | Regex replacement |
replaceFirst(regex, repl) | Only first match |
strip() / trim() | Whitespace removal (strip is Unicode-aware, Java 11+) |
stripLeading() / stripTrailing() | Side-specific |
9. Splitting Strings
| Method | Use |
split(regex) | All splits |
split(regex, limit) | Limit elements |
Pattern.compile(re).split(s) | Reuse compiled pattern |
Warning: split uses regex — escape special chars (e.g. "\\." for dot).
| Form | Example |
String.format(fmt, args) | String.format("%-10s %5d", "x", 42) |
"fmt".formatted(args) | Java 15+ |
%s %d %f %x %b %c %n | Type specifiers |
%5.2f | Width.precision |
%-10s | Left-align |
%,d | Thousands separator |
11. Converting Cases
| Method | Notes |
toLowerCase() | Uses default Locale |
toLowerCase(Locale.ROOT) | Locale-independent (recommended) |
toUpperCase(Locale) | Locale-aware |
Note: "i".toUpperCase(Locale.forLanguageTag("tr")) = "İ" (Turkish dotted I).
12. Using StringBuilder
Example: StringBuilder
StringBuilder sb = new StringBuilder();
sb.append("Hello").append(", ").append(name);
sb.insert(0, ">> ").reverse().deleteCharAt(0);
String result = sb.toString();
| Method | Effect |
append | Add to end |
insert(i, x) | Insert at index |
delete(start, end) | Remove range |
reverse | In-place reverse |
setLength(n) | Truncate or pad |
capacity() / ensureCapacity(n) | Internal buffer |
13. Using StringBuffer
| Aspect | StringBuffer | StringBuilder |
| Thread-safe | Yes (synchronized) | No |
| Speed | Slower | Faster |
| When to use | Multi-thread mutation (rare) | Default choice |
14. Working with Text Blocks JAVA 15+
Example: Text block
String json = """
{
"name": "Alice",
"age": 30
}
""";
String html = """
<div class="msg">
Hello, %s!
</div>""".formatted(name);
| Rule | Detail |
| Delimiter | Triple double-quotes """ |
| First line | Must be empty after opening """ |
| Indentation | Stripped to align with closing """ |
| Escapes | \ (line continuation), \s (significant space) |