⚡IntermediateModern Java

Modern String Methods

Use String enhancements added in Java 11-15: isBlank, strip, lines, repeat, indent, and formatted.

Overview

Java 11 through 15 added many useful String methods that eliminate the need for common workarounds. Key additions: - isBlank() / strip(): better alternatives to isEmpty() and trim() - lines(): split a string into a stream of lines - repeat(n): repeat a string n times - indent(n): adjust indentation - formatted(args): instance version of String.format() These methods work consistently across platforms and handle Unicode whitespace correctly.

Key Points

  • •isBlank() returns true if the string is empty or contains only whitespace
  • •strip() removes leading/trailing Unicode whitespace (unlike trim() which only handles ASCII)
  • •stripLeading() and stripTrailing() remove whitespace from one side only
  • •lines() returns Stream<String> of lines (handles all line terminators)
  • •repeat(n) repeats the string n times; "ab".repeat(3) = "ababab"
  • •indent(n) adds n spaces to each line; negative n removes spaces
  • •formatted(args) is equivalent to String.format(this, args)
  • •stripIndent() removes common leading whitespace (like text block processing)

Examples

Blank check and whitespace stripping

public class Main {
    public static void main(String[] args) {
        // isBlank: true for empty or whitespace-only
        System.out.println("".isBlank());          // true
        System.out.println("   ".isBlank());       // true
        System.out.println("  a  ".isBlank());     // false

        // strip vs trim
        String s = "  \t Hello World \n  ";
        System.out.println("[" + s.trim() + "]");          // [Hello World]
        System.out.println("[" + s.strip() + "]");         // [Hello World]
        System.out.println("[" + s.stripLeading() + "]");  // [Hello World \n  ]
        System.out.println("[" + s.stripTrailing() + "]"); // [  \t Hello World]

        // Practical: filter blank lines from user input
        String input = "Alice\n\n  \nBob\n   Carol";
        input.lines()
             .filter(line -> !line.isBlank())
             .map(String::strip)
             .forEach(System.out::println);
    }
}

strip() is preferred over trim() because it handles Unicode whitespace (like non-breaking space \u00A0) which trim() does not recognize.

lines(), repeat(), and indent()

public class Main {
    public static void main(String[] args) {
        // lines(): Stream<String> from a multi-line string
        String data = "one\ntwo\nthree\nfour";
        long count = data.lines().count();
        System.out.println("Line count: " + count); // 4

        data.lines()
            .map(String::toUpperCase)
            .forEach(System.out::println);

        // repeat()
        String sep = "-".repeat(30);
        System.out.println(sep);

        String row = "| %-10s | %6.2f |\n".formatted("apple", 1.99);
        System.out.print("+" + "-".repeat(14) + "+" + "-".repeat(8) + "+\n");
        System.out.print(row);
        System.out.print("+" + "-".repeat(14) + "+" + "-".repeat(8) + "+\n");

        // indent()
        String code = "int x = 1;\nint y = 2;";
        System.out.print(code.indent(4)); // each line indented 4 spaces
    }
}

lines() handles \n, \r\n, and \r line endings. It does not include an empty final element unlike split("\n") which does.

formatted() and practical string processing

import java.util.List;
import java.util.stream.Collectors;

public class Main {
    record User(String name, int age, String email) {}

    public static void main(String[] args) {
        var users = List.of(
            new User("Alice", 30, "alice@example.com"),
            new User("Bob", 25, "bob@example.com"),
            new User("Carol", 35, "carol@example.com")
        );

        // formatted() as instance method
        String template = "Name: %-10s Age: %2d Email: %s";
        users.stream()
             .map(u -> template.formatted(u.name(), u.age(), u.email()))
             .forEach(System.out::println);

        System.out.println("-".repeat(50));

        // lines() with processing
        String csv = "Alice,30\nBob,25\nCarol,35";
        csv.lines()
           .map(line -> line.split(","))
           .filter(parts -> parts.length == 2)
           .forEach(parts ->
               System.out.println("%s is %s years old".formatted(parts[0], parts[1])));
    }
}

formatted() is an instance method on String (since Java 15) that is equivalent to String.format(this, args). It can be chained directly on a template literal.

Common Mistakes

  • Using isEmpty() to check for blank strings. isEmpty() only checks length == 0; it returns false for " ". Use isBlank() when you want to treat whitespace-only strings as empty
  • Using trim() with non-ASCII whitespace. trim() only strips ASCII control characters (code points <= U+0020). strip() is correct for all Unicode whitespace
  • Using split("\n") instead of lines(). split adds an empty trailing element if the string ends with \n. lines() does not

Note

Use isBlank() and strip() consistently in all new code. They handle edge cases that trim() and isEmpty() miss. Use lines() instead of split("\n") for predictable behavior with trailing newlines.

Exercises

Write Java code and click Run to execute it instantly. When your output looks correct, mark as done.

Loading editor…

Completed: 0 / 4 exercises

Knowledge Check

Question 1 of 4

What is the difference between isBlank() and isEmpty()?