String.indent() – Left Indent a Line in Java

Lokesh Gupta

Learn to indent (left indentation) a string(s) in Java using String.indent() API. This api has been introduced in Java 12.

1. String.indent() API

The String.indent() method adjusts the indentation of each line of a given string based on the value of the count and normalizes line termination characters.

/**
* count - number of leading white space characters to add or remove
* returns - string with indentation adjusted and line endings normalized
*/
public String indent​(int count)

Note that the value of the count can be either a positive or negative number.

  • positive number – If count > 0 then spaces are inserted at the beginning of each line.
  • negative number – If count < 0 then spaces are removed at the beginning of each line.
  • negative number – If count > available white spaces then all leading spaces are removed.

Each white space character is treated as a single character. In particular, the tab character “\t” is considered a single character; it is not expanded.

2. String.indent​() Example

Java program to white strings into file indented to 8 characters. We are replacing the whitespace character with hyphen so we can notice how the spaces have been modified in the final string.

# Indent 8 spaces (to the left)

String line1 = "ABC".indent(8);
System.out.println(line1.replace(" ", "-"));

# Indent 8 spaces then -5 spaces

String line2 = "ABC".indent(8).indent(-5);
System.out.println(line2.replace(" ", "-"));

Program output.

--------ABC
---ABC

3. Left Indent a Text Block

We can use the indent() method with the text blocks as well (added in Java 15). Check out the following example:

String textBlock = """
    Line 1
    Line 2""";

String indentedBlock = """
    Line 1
    Line 2""".indent(8);

System.out.println(textBlock.replace(" ", "-"));
System.out.println(indentedBlock.replace(" ", "-"));

The program output:

Line-1
Line-2
--------Line-1
--------Line-2

Drop me your questions related to left indenting a String using the Java 12 String.indent() method.

Happy Learning !!

Source Code on Github

Comments

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode