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

JAVA
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"));
}
Output
true
true
true
14
22

Changing case and cleaning up

JAVA
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");
}
Output
[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

JAVA
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('-', '/'));
}
Output
green apples and green cherries
ripe apples and red cherries
2026/03/05

Splitting and joining

JAVA
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));
}
Output
3
Berlin
Lisbon | Berlin | Dublin

split takes a regular expression, so special characters like . or | must be escaped: split("\\.") (lesson 53).

Formatting with formatted

JAVA
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));
}
Output
Mug x3 = 37.50 EUR
Mug       |  12.5|
00042
1,234,567
SpecifierMeaning
%sAny value as text
%dWhole number
%.2fDecimal with 2 places
%10s / %-10sRight / left aligned in 10 characters
%05dPad with zeros to width 5
%,dThousands separators
%nLine 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

JAVA
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());
}
Output
[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

JAVA
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());
}
Output
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.

Try it yourself · Main.java
Edit the code, copy it into Main.java and run java Main.java (Java 25+). How to set up Java
Output
ten-tips-for-clean-java-code
ten-tips-for-clean-java-code  28 chars