Java 11 String API Additions

1. Introduction

Java 11 added few useful APIs to the commonly used String class. In this tutorial, we will explore and use these new APIs.

2. repeat()

As the name suggests, the repeat() instance method repeats the string content.

It returns a string whose value is the concatenation of the string repeated n times, where n is passed as a parameter:

@Test
public void whenRepeatStringTwice_thenGetStringTwice() {
    String output = "La ".repeat(2) + "Land";

    is(output).equals("La La Land");
}

Additionally, repeat() returns an empty string if the string is empty or the count is zero.

3. strip()*

The strip() instance method returns a string with all leading and trailing whitespaces removed:

@Test
public void whenStripString_thenReturnStringWithoutWhitespaces() {
    is("\n\t  hello   \u2005".strip()).equals("hello");
}

Java 11 also added methods stripLeading() and stripTrailing(), which handle leading and trailing whitespaces, respectively.

3.1. Difference Between strip() and trim()

strip*() determines whether the character is whitespace or not based on Character.isWhitespace(). In other words, it is aware of Unicode whitespace characters.

This is different from trim(), which defines space as any character that is less than or equal to the Unicode space character (U+0020). If we use trim() in the previous example, we will get a different result:

@Test
public void whenTrimAdvanceString_thenReturnStringWithWhitespaces() {
    is("\n\t  hello   \u2005".trim()).equals("hello   \u2005");
}

Notice how trim() was able to trim the leading whitespace, but it didn’t trim the trailing whitespace. This is because trim() is not aware of Unicode whitespace characters and hence does not consider ‘\u2005′ a whitespace character.

4. isBlank()

The isBlank() instance method returns true if the string is empty or contains only whitespace. Otherwise, it returns false:

@Test
public void whenBlankString_thenReturnTrue() {
    assertTrue("\n\t\u2005  ".isBlank());
}

Similarly, the isBlank() method is aware of Unicode whitespace characters, just like strip().

5. lines()

The lines() instance method returns a Stream of lines extracted from the string, separated by line terminators:

@Test
public void whenMultilineString_thenReturnNonEmptyLineCount() {
    String multilineStr = "This is\n \n a multiline\n string.";

    long lineCount = multilineStr.lines()
      .filter(String::isBlank)
      .count();

    is(lineCount).equals(3L);
}

A line terminator is one of the following: “\n”, “\r”, or “\r\n”.

The stream contains lines in the order in which they occur. The line terminator is removed from each line.

This method should be preferred over split(), as it provides better performance for breaking multi-line input.

6. Conclusion

In this quick article, we explored the new String APIs in Java 11.

Finally, code snippets can be found over on GitHub.

Leave a Reply

Your email address will not be published.