Java String indent() Method Example

In this source code example, we will demonstrate the usage of Java 12 introduced indent() method of String class.

To indent a string, we used to write a small helper method that put the desired number of spaces in front of the String. If it should work over multiple lines, the method became correspondingly complex.

JDK 12 introduced indent() method in Java.lang.String class. This method is useful to add or remove white spaces from the beginning of the line to adjust indentation for each string line.

Java String indent() Method Example

The following example shows how to indent a multiline string by four spaces:
public class StringIndentDemo {
    public static void main(String[] args) {

        String s = "I am\na multiline\nString.";
        System.out.println(s);
        String newStr = s.indent(4);
        System.out.println(newStr);

        String s1 = "source code examples";
        System.out.println(s1);
        System.out.println(s1.indent(5));
    }
}

Output:

I am
a multiline
String.
    I am
    a multiline
    String.

source code examples
     source code examples

Comments