Java 11: New Methods in String Class With Examples

Java 11 doesn’t have a lot of language specific features. So, it was surprising to see 6 new methods getting introduced in Java String Class.

Java 11 String Class New Methods

Let’s look at these new String class methods one by one.

    1. isBlank(): This method returns true if the string is empty or contains only white spaces code points.

Output:

Notice that “t” is considered as a white space character codepoint in Unicode.

java-string-isblank

Java String IsBlank()

I am using jShell to execute the code snippets without actually creating a java file.

    1. lines(): This method returns a stream of lines extracted from the string, separated by line terminators such as n, r etc.

Output:

java-string-lines-function

Java String lines() Function

This method is useful to process multi-line strings with one line at a time.

    1. strip(), stripLeading(), stripTrailing(): These methods are used to strip whitespaces from the string. As the name suggests, strip() will remove leading and trailing whitespaces. However, stripLeading() will remove only leading whitespaces and stripTrailing() will remove only trailing whitespaces.

Output:

Java String strip(), stripLeading(), stripTrailing()

    1. repeat(int n): This method returns a new string whose value is the concatenation of this string repeated ‘n’ times.

Output:

java-string-repeat

Java String repeat()

Conclusion

Java String class has a lot of utility methods. However, all these new utility methods will be very useful because we won’t have to worry about writing them ourselves and thinking about whether they cover all the rare scenarios related to different types of Unicode characters or not.

Reference: Java 11 String Class API Doc

By admin

Leave a Reply

%d bloggers like this: