Java 11 introduced several new methods in the java.lang.String
class. Here's a detailed explanation of each:
isBlank(): This method checks if a string is empty or contains only white space characters. It's a more comprehensive check than the
isEmpty()
method, which only checks if a string is empty." ".isBlank(); // returns true "".isBlank(); // returns true "Hello".isBlank(); // returns false
Before Java 11, to check if a string was blank, you would have to use something like
str.trim().isEmpty()
, which is not as clear or efficient.lines(): This method returns a stream of lines extracted from the string, separated by line terminators (
\n
,\r
,\r\n
)."Hello\nWorld".lines().forEach(System.out::println); // prints: // Hello // World
Before Java 11, you would have to use something like
str.split("\n")
to split a string into lines, which returns an array, not a stream, and doesn't handle different line terminators.strip(), stripLeading(), stripTrailing(): These methods remove white space from the string.
strip()
removes white space from both ends of the string,stripLeading()
from the beginning, andstripTrailing()
from the end. These methods consider a wider range of white space characters thantrim()
." Hello World ".strip(); // returns "Hello World" " Hello World ".stripLeading(); // returns "Hello World " " Hello World ".stripTrailing(); // returns " Hello World"
Before Java 11, you would use the
trim()
method to remove white space from both ends of a string. However,trim()
only removes ASCII space characters (code 32), whilestrip()
methods remove all kinds of white space.repeat(int n): This method repeats the string
n
times."Hello".repeat(3); // returns "HelloHelloHello"
Before Java 11, to repeat a string, you would have to use a loop or a third-party library like Apache Commons Lang.
Post a Comment