Java 11 String Methods: isBlank, lines, strip, repeat
Introduction
Java 11 added six new methods to the
(Note - This tutorial is part of the Java 11 series. To see all the features of the release, read the overview of new features in Java 11Click to read tutorial: Overview of New Features in Java 11.) isBlank() - checking for empty or whitespace-only strings Definition of String.isBlank()
OUTPUT of the above code
Explanation of the code
strip(), stripLeading() and stripTrailing()
OUTPUT of the above code
Explanation of the code
OUTPUT of the above code
Explanation of the code
repeat() - repeating a string n times
Definition of String.repeat()
OUTPUT of the above code
Explanation of the code
OUTPUT of the above code
Summary
In this tutorial we went through the String methods added in Java 11. We saw that
String class - isBlank(), lines(), strip(), stripLeading(), stripTrailing() and repeat(). This tutorial explains the new String methods in Java 11 with examples. We will first see how isBlank() differs from isEmpty(). Next we will look at the three strip methods, and why strip() is not the same as the old trim(). We will then process multi-line text with lines(), and lastly build strings with repeat().(Note - This tutorial is part of the Java 11 series. To see all the features of the release, read the overview of new features in Java 11Click to read tutorial: Overview of New Features in Java 11.) isBlank() - checking for empty or whitespace-only strings Definition of String.isBlank()
public boolean isBlank()isBlank() returns true if the string is empty or contains only whitespace. isEmpty(), which has been there since Java 6, returns true only when the length is zero. Before Java 11 the usual way to check for a blank string was str.trim().isEmpty(), which creates a new string just to throw it away.
isBlank() vs isEmpty()
//IsBlankDemo.java
public class IsBlankDemo {
public static void main(String[] args) {
String[] inputs = {"", " ", "\t\n", "\u2003", " Java "};
for (String s : inputs) {
System.out.printf("%-12s isEmpty=%-5b isBlank=%b%n",
"[" + s.replace("\t", "\\t").replace("\n", "\\n").replace("\u2003", "\\u2003") + "]",
s.isEmpty(), s.isBlank());
}
}
}
[] isEmpty=true isBlank=true [ ] isEmpty=false isBlank=true [\t\n] isEmpty=false isBlank=true [\u2003] isEmpty=false isBlank=true [ Java ] isEmpty=false isBlank=false
- Only the empty string
""is empty, but the strings holding spaces, a tab and a newline, and\u2003(an em space) are all blank. isBlank()usesCharacter.isWhitespace(int)to decide what whitespace is, so it understands Unicode whitespace such as the em space, not just the ASCII space." Java "has non-whitespace characters, so it is neither empty nor blank.
strip() removes whitespace from both ends of a string, stripLeading() only from the start, and stripTrailing() only from the end. That sounds exactly like trim(), but there is an important difference -
trim()removes every character whose code is less than or equal toU+0020(the space). That covers the ASCII space and control characters, but not Unicode whitespace such as the em space or the ideographic space used in Chinese and Japanese text.strip()removes the characters for whichCharacter.isWhitespace()returnstrue, so it is Unicode-aware.
strip() vs trim()
//StripDemo.java
public class StripDemo {
public static void main(String[] args) {
String ascii = " Java 11 ";
System.out.println("[" + ascii.trim() + "]");
System.out.println("[" + ascii.strip() + "]");
System.out.println("[" + ascii.stripLeading() + "]");
System.out.println("[" + ascii.stripTrailing() + "]");
// \u3000 is the IDEOGRAPHIC SPACE, a Unicode whitespace character
String unicode = "\u3000Java 11\u3000";
System.out.println("trim() length: " + unicode.trim().length());
System.out.println("strip() length: " + unicode.strip().length());
}
}
[Java 11] [Java 11] [Java 11 ] [ Java 11] trim() length: 9 strip() length: 7
- For ASCII spaces,
trim()andstrip()give the same result.stripLeading()andstripTrailing()keep the spaces on one side. "\u3000Java 11\u3000"has 9 characters.trim()leaves it unchanged, sinceU+3000is greater thanU+0020, whilestrip()removes both ideographic spaces and leaves the 7 characters of"Java 11".- Like all
Stringmethods, the strip methods return a new string and leave the original unchanged. If there is nothing to strip, they return the original string itself.
strip() over trim() in new code, especially for text typed by users or read from files, which may contain Unicode whitespace.
lines() - a stream of the lines in a string
Definition of String.lines()
public Stream<String> lines()lines() splits a string into lines and returns them as a Stream<String>. A line ends at \n, \r or \r\n, and the line terminators are not included in the lines. Since it returns a stream, you can directly apply the Java 8 Streams APIClick to read: Java 8 Streams API operations such as filter() and map() to the lines.
Processing multi-line text with lines()
//LinesDemo.java
import java.util.stream.Collectors;
public class LinesDemo {
public static void main(String[] args) {
// Windows (\r\n), Unix (\n) and old Mac (\r) line endings mixed together
String report = "Name,Marks\r\nTom,78\nHarry,91\r\n\rSam,64\n";
System.out.println("Line count: " + report.lines().count());
String toppers = report.lines()
.skip(1) // skip the header
.filter(line -> !line.isBlank()) // ignore empty lines
.map(line -> line.split(","))
.filter(cols -> Integer.parseInt(cols[1]) >= 75)
.map(cols -> cols[0])
.collect(Collectors.joining(", "));
System.out.println("Scored 75 or more: " + toppers);
}
}
Line count: 5 Scored 75 or more: Tom, Harry
reportmixes all three kinds of line endings, andlines()handles each of them.\r\nis treated as a single terminator, so it does not create an extra empty line.- The count is 5: the header, three data lines and the empty line between
\r\nand\r. The final\nends the last line - it does not start a new, empty one. filter(line -> !line.isBlank())uses the newisBlank()method to drop the empty line before it is parsed.lines()is lazy: it finds the line breaks as the stream is consumed, rather than splitting the whole string up front assplit("\\R")does. This makes it faster for large strings, especially when the stream stops early.
public String repeat(int count)repeat(count) returns the string concatenated with itself count times. A count of 0 returns an empty string, and a negative count throws an IllegalArgumentException. Before Java 11 this needed a loop with a StringBuilder, or a library such as Apache Commons Lang.
Building strings with repeat()
//RepeatDemo.java
public class RepeatDemo {
public static void main(String[] args) {
System.out.println("=".repeat(20));
System.out.println("ab".repeat(3));
System.out.println("[" + "x".repeat(0) + "]");
// A simple text bar chart
String[] names = {"Tom", "Harry", "Sam"};
int[] marks = {78, 91, 64};
for (int i = 0; i < names.length; i++) {
System.out.printf("%-6s %s %d%n", names[i], "#".repeat(marks[i] / 10), marks[i]);
}
try {
"x".repeat(-1);
} catch (IllegalArgumentException e) {
System.out.println("repeat(-1) -> " + e.getMessage());
}
}
}
==================== ababab [] Tom ####### 78 Harry ######### 91 Sam ###### 64 repeat(-1) -> count is negative: -1
"=".repeat(20)is a quick way to print a separator line, and"ab".repeat(3)repeats a multi-character string.- The bar chart uses
repeat()with a count computed at runtime - one#for every 10 marks. repeat(-1)throws anIllegalArgumentExceptionwith the message shown.
Character.toString(int codePoint), which converts a Unicode code point to a String. Unlike Character.toString(char), it works for characters outside the Basic Multilingual Plane, such as emoji, which need two chars.
Converting a code point to a String
//CodePointDemo.java
public class CodePointDemo {
public static void main(String[] args) {
String a = Character.toString(65); // 'A'
String face = Character.toString(0x1F600); // an emoji, outside the BMP
System.out.println(a + " has length " + a.length());
System.out.println("U+1F600 has length " + face.length()
+ " and " + face.codePointCount(0, face.length()) + " code point");
}
}
A has length 1 U+1F600 has length 2 and 1 code point
isBlank() returns true for whitespace-only strings, unlike isEmpty(). We then compared strip(), stripLeading() and stripTrailing() with trim(), and saw that only the strip methods remove Unicode whitespace. Next we processed text with mixed line endings using lines() and streams, and built strings with repeat(). Lastly, we converted a code point to a string with Character.toString(int). In the next tutorial, we will see how Java 11 allows var in lambda parametersClick to read tutorial: Java 11 var in Lambda Parameters with Examples.Continue Reading Java 11 Tutorials
Java 11 var in Lambda Parameters with ExamplesClick to read tutorial: Java 11 var in Lambda Parameters with Examples Overview of New Features in Java 11Click to read tutorial: Overview of New Features in Java 11 Java 11: Run Single-File Source Code Programs with javaClick to read tutorial: Java 11: Run Single-File Source Code Programs with java Java 11 API Additions: Files.readString, Predicate.notClick to read tutorial: Java 11 API Additions: Files.readString, Predicate.not Java 11 HTTP Client API Tutorial with ExamplesClick to read tutorial: Java 11 HTTP Client API Tutorial with Examples Java 11 Removed Modules: Java EE, CORBA and JavaFXClick to read tutorial: Java 11 Removed Modules: Java EE, CORBA and JavaFX
Java 11 var in Lambda Parameters with ExamplesClick to read tutorial: Java 11 var in Lambda Parameters with Examples Overview of New Features in Java 11Click to read tutorial: Overview of New Features in Java 11 Java 11: Run Single-File Source Code Programs with javaClick to read tutorial: Java 11: Run Single-File Source Code Programs with java Java 11 API Additions: Files.readString, Predicate.notClick to read tutorial: Java 11 API Additions: Files.readString, Predicate.not Java 11 HTTP Client API Tutorial with ExamplesClick to read tutorial: Java 11 HTTP Client API Tutorial with Examples Java 11 Removed Modules: Java EE, CORBA and JavaFXClick to read tutorial: Java 11 Removed Modules: Java EE, CORBA and JavaFX