Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – Black Friday 2026 – NPI EA – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

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:

  1. The string is conceptually separated into lines using lines(), a method added to the String API in Java 11.
  2. 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.
  3. 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.
Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

Course – Black Friday 2026 – NPI EA – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW