Let's get started with a Microservice Architecture with Spring Cloud:
Java String API – New Methods
Last updated: January 8, 2024
1. Introduction
The String class provides a set of APIs for string manipulation and processing. Java 11 and 12 added a few new useful APIs to the String class, enhancing its capabilities.
In this tutorial, we’ll explore and use these commonly used APIs for String manipulation introduced in Java 11 and 12.
2. indent()
The indent() method adjusts the indentation of each line of the string based on the argument passed to it.
When indent() is called on a string, the following actions are taken:
- The string is conceptually separated into lines using lines(), a method added to the String API in Java 11.
- Each line is then adjusted based on the int argument n passed to it and then suffixed with a line feed “\n”.
- If n > 0, then n spaces are inserted at the beginning of each line.
- If n < 0, then up to n white space characters are removed from the beginning of each line. In case a given line does not contain sufficient white space, then all leading white space characters are removed.
- If n == 0, then the line remains unchanged. However, line terminators are still normalized.
- The resulting lines are then concatenated and returned.
For example:
@Test
public void whenPositiveArgument_thenReturnIndentedString() {
String multilineStr = "This is\na multiline\nstring.";
String outputStr = " This is\n a multiline\n string.\n";
String postIndent = multilineStr.indent(3);
assertThat(postIndent, equalTo(outputStr));
}
We can also pass a negative int to reduce the indentation of the string. For example:
@Test
public void whenNegativeArgument_thenReturnReducedIndentedString() {
String multilineStr = " This is\n a multiline\n string.";
String outputStr = " This is\n a multiline\n string.\n";
String postIndent = multilineStr.indent(-2);
assertThat(postIndent, equalTo(outputStr));
}
Here, we reduce the indentation by 2.
3. transform()
The transform() method allows us to apply a function to the string on which it’s called. The function should expect a single String argument and produce a result:
@Test
public void whenTransformUsingLamda_thenReturnTransformedString() {
String result = "hello".transform(input -> input + " world!");
assertThat(result, equalTo("hello world!"));
}
It is not necessary that the output has to be a string. For example:
@Test
public void whenTransformUsingParseInt_thenReturnInt() {
int result = "42".transform(Integer::parseInt);
assertThat(result, equalTo(42));
}
In the code above, we parse a string to an integer using the transform() method and method reference.
4. 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.
5. strip()
The strip() instance method returns a string with all leading and trailing whitespace 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 whitespace, respectively.
5.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’ll 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.
6. 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().
7. lines()
The lines() instance method returns a Streamof 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 “\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.
8. Conclusion
In this article, we explored the new String APIs in Java 11 and 12. These new APIs provide more capabilities for manipulating Java String values.
The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
















