String Methods & Formatting
The String class has dozens of useful methods for searching, cleaning, splitting and joining text. This lesson tours the most important ones, then covers formatting numbers and text neatly with formatted, and building strings efficiently with StringBuilder.
Searching
void main() { String title = "Learning Java Step by Step"; System.out.println(title.contains("Java")); System.out.println(title.startsWith("Learn")); System.out.println(title.endsWith("Step")); System.out.println(title.indexOf("Step")); System.out.println(title.lastIndexOf("Step")); }
true true true 14 22
Changing case and cleaning up
void main() { String input = " Ana Pereira "; System.out.println("[" + input.strip() + "]"); System.out.println(input.strip().toLowerCase()); System.out.println(" ".isBlank()); System.out.println("na".repeat(4) + " Batman"); }
[Ana Pereira] ana pereira true nananana Batman
strip() removes leading and trailing whitespace (the older trim() only handles ASCII spaces). isBlank() is true for empty or whitespace-only strings.
Replacing
void main() { String text = "red apples and red cherries"; System.out.println(text.replace("red", "green")); System.out.println(text.replaceFirst("red", "ripe")); System.out.println("2026-03-05".replace('-', '/')); }
green apples and green cherries ripe apples and red cherries 2026/03/05
Splitting and joining
void main() { String csv = "Lisbon,Berlin,Dublin"; String[] cities = csv.split(","); System.out.println(cities.length); System.out.println(cities[1]); System.out.println(String.join(" | ", cities)); }
3 Berlin Lisbon | Berlin | Dublin
split takes a regular expression, so special characters like . or | must be escaped: split("\\.") (lesson 53).
Formatting with formatted
void main() { String name = "Mug"; double price = 12.5; int qty = 3; System.out.println("%s x%d = %.2f EUR".formatted(name, qty, price * qty)); System.out.println(String.format("%-10s|%6.1f|", name, price)); System.out.printf("%05d%n", 42); System.out.println("%,d".formatted(1234567)); }
Mug x3 = 37.50 EUR Mug | 12.5| 00042 1,234,567
| Specifier | Meaning |
|---|---|
%s | Any value as text |
%d | Whole number |
%.2f | Decimal with 2 places |
%10s / %-10s | Right / left aligned in 10 characters |
%05d | Pad with zeros to width 5 |
%,d | Thousands separators |
%n | Line break |
"…".formatted(…) (Java 15+), String.format(…) and System.out.printf(…) all use the same specifiers. Separators and decimal points follow the computer's locale unless you pass one, e.g. String.format(Locale.GERMANY, …).
StringBuilder
void main() { StringBuilder sb = new StringBuilder(); for (int i = 1; i <= 5; i++) { sb.append(i); if (i < 5) sb.append(", "); } sb.insert(0, "[").append("]"); System.out.println(sb); System.out.println(sb.reverse()); }
[1, 2, 3, 4, 5] ]5 ,4 ,3 ,2 ,1[
Because strings are immutable, adding to a string in a loop creates a new string each time. StringBuilder is a mutable buffer: append, insert, delete and reverse, then call toString() (or print it). Use it when building text piece by piece in loops.
Characters of a string
void main() { String word = "Mississippi"; int count = 0; for (char c : word.toCharArray()) { if (c == 's') count++; } System.out.println(count); System.out.println(word.chars().filter(c -> c == 'i').count()); }
4 4
Loop over toCharArray(), or use chars() with streams (lesson 46).
Try it yourself
Turn a sentence into a URL "slug" and print a formatted report line.
ten-tips-for-clean-java-code ten-tips-for-clean-java-code 28 chars