Java 11 String Class New Methods
Let’s look at these new String class methods one by one.
- isBlank(): This method returns true if the string is empty or contains only white spaces code points.
- lines(): This method returns a stream of lines extracted from the string, separated by line terminators such as \n, \r etc.
- 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.
- repeat(int n): This method returns a new string whose value is the concatenation of this string repeated ‘n’ times.
String s = "abc"; System.out.println(s.isBlank()); s = ""; System.out.println(s.isBlank()); s = "\t \t"; System.out.println(s.isBlank());
false true true
Notice that “\t” is considered as a white space character codepoint in Unicode.
I am using jShell to execute the code snippets without actually creating a java file.
String s1 = "Hi\nHello\rWassup"; System.out.println(s1); List
lines = s1.lines().collect(Collectors.toList()); System.out.println(lines);
This method is useful to process multi-line strings with one line at a time.
String s2 = " Hello, \tWorld\t "; System.out.println("#" + s2 + "#"); System.out.println("#" + s2.strip() + "#"); System.out.println("#" + s2.stripLeading() + "#"); System.out.println("#" + s2.stripTrailing() + "#");
# Hello, World # #Hello, World# #Hello, World # # Hello, World#
String s3 = "Hello\n"; System.out.println(s3.repeat(3)); s3 = "Do"; System.out.println(s3.repeat(2));
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