Java String indent() Method Examples

Java String indent() method is used to indent every line in the string and normalize the newline characters. This method was added to String class in Java 12 release.


Working of String indent(int n) Method

  • The string is divided into lines using the lines() method.
  • Each line is then indented based on the indentation value.
  • If n > 0, then n spaces (U+0020) are added at the beginning of each line.
  • If n < 0, then up to ‘n’ white space characters are removed from the beginning of the line. Note that the tab character (\t) is treated as a single character. If the line doesn’t have enough leading white spaces, then all the leading white spaces are removed.
  • If n = 0, then the lines remain unchanged.
  • Finally, all the lines are suffixed with ‘\n’, concatenated and returned.
  • If the string is empty, then the empty string is returned.

Below image shows how the indent() method works for a string.

Java String Indent Working
Java String indent() Working

Java String indent() Method Examples

Let’s look into some examples of using string indent() method.

1. indent() argument is a positive integer

jshell> String str = "12345\n123\r11\n\r22";
str ==> "12345\n123\r11\n\r22"

jshell> String str1 = str.indent(2);
str1 ==> "  12345\n  123\n  11\n  \n  22\n"

This example resembles the same thing as in the above illustration image.


2. indent() argument is a negative integer

jshell> String str = "   Hi\nHello\r\t\t\tYes";
str ==> "   Hi\nHello\r\t\t\tYes"

jshell> String str1 = str.indent(-2);
str1 ==> " Hi\nHello\n\tYes\n"

3. String is empty

jshell> String empty = "";
empty ==> ""

jshell> empty.indent(2);
$59 ==> ""

jshell> empty.indent(-2);
$60 ==> ""

The indent() method has no effect on an empty string.


4. indent() argument is zero

jshell> String str = "Java\n Python\r \tAndroid";
str ==> "Java\n Python\r \tAndroid"

jshell> String str1 = str.indent(0);
str1 ==> "Java\n Python\n \tAndroid\n"

If the indent() argument is 0, only the line terminators are normalized.


Conclusion

Java String indent() is a utility method to add whitespaces into each line of the string. We can easily write a utility method to perform the same thing. It would have been nice if there would have been an option to indent at the end of the line too.

References: