Java String indent()

In this guide, you will learn about the String indent() method in Java programming and how to use it with an example.

1. String indent() Method Overview

Definition:

The indent(int n) method is a part of the String class in Java. This method adjusts the indentation of each line of the invoking string based on the value of n and normalizes line termination characters.

Syntax:

String indent(int n)

Parameters:

- n: The number of spaces by which to adjust the indentation. If n is positive, the lines are indented by n spaces. If n is negative, the lines are unindented by n spaces. If n is zero, the method only normalizes the line terminators.

Key Points:

- The method returns a string with adjusted indentation.

- The method uses the \n character to denote line breaks.

- If n is negative and exceeds the amount of leading whitespace, the line will have no leading whitespace.

- The method is available from Java 12 onwards.

2. String indent() Method Example

public class IndentExample {
    public static void main(String[] args) {
        String str = "Java\nProgramming\nLanguage";
        System.out.println("Original String:\n" + str);

        // Indenting the string by 4 spaces
        String indentedString = str.indent(4);
        System.out.println("Indented String:\n" + indentedString);

        // Unindenting the string by 2 spaces
        String unindentedString = indentedString.indent(-2);
        System.out.println("Unindented String:\n" + unindentedString);
    }
}

Output:

Original String:
Java
Programming
Language
Indented String:
    Java
    Programming
    Language
Unindented String:
  Java
  Programming
  Language

Explanation:

In this example, we have a multi-line string str. We first print the original string. Then, we use the indent() method to add 4 spaces to the start of each line of the string and print the indented string. 

Next, we unindent the indented string by 2 spaces using indent(-2) and print the resulting unindented string. The output shows the original, indented, and unindented strings.

Comments