Java String indent() Method Example

1. Introduction

The String.indent() method, introduced in Java 12, adjusts the indentation of each line of the calling string according to the specified number of spaces. It can be used to increase or decrease the indentation, and it also adds line terminators if absent. This method is particularly useful for formatting output or creating text-based UI components.

Key Points

- indent(int n) adjusts the indentation based on the number of spaces specified by n. If n is positive, spaces are added; if n is negative, spaces are removed.

- It normalizes line termination sequences to \n and applies the indentation uniformly to all lines in the string.

- Each line of the string after calling indent() will start with n spaces if n is positive.

2. Program Steps

1. Create a multiline string.

2. Use the indent() method to adjust the string’s indentation.

3. Print the original and the indented string.

3. Code Program

public class StringIndentExample {
    public static void main(String[] args) {
        // Multiline string
        String text = "Java\nString\nindent\nMethod";

        // Increase indentation by 4 spaces
        String indentedText = text.indent(4);

        // Print the results
        System.out.println("Original text:");
        System.out.println(text);
        System.out.println("Indented text:");
        System.out.println(indentedText);
    }
}

Output:

Original text:
Java
String
indent
Method
Indented text:
    Java
    String
    indent
    Method

Explanation:

1. String text = "Java\\nString\\nindent\\nMethod";: Creates a string with multiple lines, separated by newline characters.

2. String indentedText = text.indent(4);: Calls the indent() method with an argument of 4, which adds four spaces to the beginning of each line in the original string.

3. The System.out.println calls display the original and indented text. The indented text shows each line prefixed with four spaces, demonstrating the effect of the indent() method.


Comments