New String Methods in Java 11


1. isBlank()

Checks if a string is empty or contains only whitespace characters.

String s1 = "   ";
String s2 = "Hello";

System.out.println(s1.isBlank()); // true
System.out.println(s2.isBlank()); // false

Difference from isEmpty():
isEmpty() only checks if the length is 0. isBlank() considers spaces, tabs, and newlines as blank.


2. lines()

Returns a stream of lines extracted from the string, split by line terminators (\n, \r, or \r\n).

String multiLine = "Java\nPython\nC++";
multiLine.lines().forEach(System.out::println);

Output:

Java
Python
C++

3. strip(), stripLeading(), stripTrailing()

Removes whitespace from the beginning, end, or both, similar to trim(), but more Unicode-friendly.

String s = "\u2000Hello\u2000"; // \u2000 is a Unicode space
System.out.println(s.strip());          // "Hello"
System.out.println(s.stripLeading());   // "Hello\u2000"
System.out.println(s.stripTrailing());  // "\u2000Hello"

Note: trim() only removes ASCII spaces (\u0020).


4. repeat(int count)

Repeats the string count times.

String s = "Hi! ";
System.out.println(s.repeat(3)); // Hi! Hi! Hi! 

Throws IllegalArgumentException if count is negative.


5. indent(int n)

Adds indentation to each line in the string. Positive numbers add spaces; negative numbers remove them.

String s = "Java\nPython";
System.out.println(s.indent(4));

Output:

    Java
    Python

6. strip(), isBlank(), and lines() in combination

You can combine the new methods for cleaner processing:

String text = "  Java\n  Python  \n  C++  ";
text.lines()
    .map(String::strip)
    .filter(line -> !line.isBlank())
    .forEach(System.out::println);

Output:

Java
Python
C++

✅ These methods make string handling more expressive and easier in Java 11.

Leave a Reply