Course contentsShow
← Java
Lesson 2221 of 2,87043. String Handling in DepthFree lesson

The indent Method: Adding Leading Whitespace

Use indent(n) to add n spaces to each line of a multiline string, preserving existing indentation structure.

The indent Method: Adding Leading Whitespace

What you'll learn: How to programmatically add leading whitespace to every line of a multiline string while preserving its existing indentation structure.

What Is indent()?

The indent(int n) method, introduced in Java 12, shifts each line of a string to the right (or left) by adding (or removing) a specified number of spaces. Think of it like adjusting the margins in a word processor—you're moving the entire block of text without changing its internal structure.

Unlike manually concatenating spaces, indent() intelligently handles multiline strings, processing each line individually while maintaining the relative indentation between lines.

How It Works

When you call indent(n):

  • Positive n: Adds n spaces to the beginning of each line
  • Negative n: Removes up to n spaces from each line (won't remove non-whitespace)
  • Preserves structure: Existing indentation differences between lines remain intact
String code = "public void hello() {\n    System.out.println(\"Hi\");\n}";

// Add 4 spaces to each line
String indented = code.indent(4);
// Result:
//     public void hello() {
//         System.out.println("Hi");
//     }

// Remove 2 spaces from each line (if they exist)
String dedented = indented.indent(-2);

Common Use Cases

  • Code generation: Adding proper indentation to generated source code
  • Formatting nested structures: XML, JSON, or configuration files
  • Text alignment: Preparing multi-line strings for display in columns

Key Takeaway: Use indent(n) to shift all lines of a multiline string by adding or removing leading whitespace uniformly, making it invaluable for formatting structured text programmatically.