Java String indent() Method Tutorial

In this section, we will learn what the String indent() method is and how to use it in Java.

What is Java String indent() Method?

The Java String indent() method is used to add indentation at the beginning of a string value.

Note: this method doesn’t change the original string value but instead returns a new one as a result.

Java indent() Method Syntax:

public String indent(int n)

indent() Method Parameters:

The method takes one argument, and that is the number of white spaces that we want to add at the beginning of a string value.

Notes:

  • If we set a positive value for this method, it will indent (add white spaces) to the beginning of a string value.
  • If we set a negative value for this method, it will remove white spaces from the beginning of a string value (If any).
  • The value 0 won’t change the target string value.

indent() Method Return Value:

The return value of this method is a copy of the original string where we added/ removed white spaces at the begging of the string.

indent() Method Exceptions:

The method does not throw an exception.

Example: using String indent() method

import java.util.stream.Stream;

public class Main {

   public static void main(String[] args) throws Exception{

      String example = "This is a simple example";
      String indented = example.indent(10);
      System.out.println(indented);
   }
}

Output:

This is a simple example

As you can see, the final string value is indented with 10 white spaces because of the value 10 we’ve set as the argument of the `indent()` method.

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies