Modern String Methods in Java

Naveen AnamaneniUpdated · 4 min read

For years, simple jobs such as "is this input only spaces?" or "draw a line of 40 dashes" needed a loop or an extra library. Java 11 and later versions added small methods to String that do these jobs in one call. They're worth learning because they make code shorter and handle tricky cases, like international spaces, that the older methods miss.

The New Methods in Action

Modern.java▶ Try it
public class Modern {
    public static void main(String[] args) {
        System.out.println("".isBlank() + " " + "  \t".isBlank()
            + " " + " a ".isBlank());
 
        System.out.println("[" + "  x ".strip() + "|"
            + "  x ".stripLeading() + "|" + "  x ".stripTrailing() + "]");
 
        System.out.println("-".repeat(20));
 
        System.out.println("line1\nline2\r\nline3".lines().toList());
 
        System.out.println("Hi %s, total Rs. %d".formatted("Srihitha", 450));
    }
}
Output
true true false
[x|x |  x]
--------------------
[line1, line2, line3]
Hi Srihitha, total Rs. 450

How it works

  1. isBlank() (Java 11) is true for empty text and text made only of spaces, tabs or newlines. isEmpty() is only true for "".
  2. strip(), stripLeading() and stripTrailing() (Java 11) remove white space at both ends, the start only, or the end only.
  3. repeat(n) (Java 11) repeats the text n times; perfect for separator lines.
  4. lines() (Java 11) splits text into lines, understanding \n, \r\n and \r, and returns a stream (turned into a list here).
  5. formatted(...) (Java 15) is String.format written as a method on the template.

Why strip Is Better Than trim

trim() dates from Java 1.0 and only removes characters with codes up to 32 (the plain ASCII space and control characters). Text copied from websites or documents often contains other Unicode spaces, such as the "em space" ( ), which trim leaves behind:

Spaces.java▶ Try it
public class Spaces {
    public static void main(String[] args) {
        String fromWeb = " Advitha ";
        System.out.println(fromWeb.trim().length());
        System.out.println(fromWeb.strip().length());
    }
}
Output
9
7

trim removed nothing, so the length is still 9; strip removed both Unicode spaces, leaving the 7 letters of "Advitha". Comparing user input with trim could make "Advitha" not equal to "Advitha".

Quick Reference

MethodSinceWhat it does
isBlank()Java 11True if empty or only white space
strip(), stripLeading(), stripTrailing()Java 11Remove Unicode white space from the ends
repeat(n)Java 11The text repeated n times
lines()Java 11A stream of lines
indent(n)Java 12Add (or remove, if negative) n spaces at the start of each line
transform(f)Java 12Apply a function to the string: s.transform(String::strip)
formatted(args)Java 15Same as String.format(this, args)
translateEscapes()Java 15Turn \t, \n written as text into real tabs and newlines
stripIndent()Java 15Remove common leading spaces from every line, as text blocks do

Common Mistakes

Using isEmpty() to reject blank input. " " is not empty; use isBlank().

Mixing trim and strip in one project. Pick strip for consistency.

Forgetting lines() returns a stream. Call .toList() or .count() on it.

Practice

  1. Easy: Print a receipt header: 30 equals signs, the shop name, then 30 equals signs, using repeat.
  2. Harder: Given a multi-line string of names, some blank lines and some with extra spaces, print each non-blank name stripped and numbered, using lines(), strip() and isBlank().

Quick check: Modern String methods

4 questions
1What does " ".isBlank() return?
2What does "ab".repeat(3) return?
3Why prefer strip() over trim()?
4What does "Hi %s".formatted("Navika") return?

Key Takeaways

Was this tutorial helpful?

Lesson 195 of 482