Java 12 String API indent​() Method Example


A Quick Guide to java.lang.String indent​() method introduced in Java 12 version as part of JDK 12. Indent() method indents the string by give number of white spaces at left side or beginning of String.

1. Overview

In this quick tutorial, We'll learn new indent() introduced in JDK 12 in Java.lang.String class.

Demonstrated with examples how to use indent() method.

Please read article on Java 12 new String API methods addition.

Will go through its internal code and how it works.

Java 12 String indent​() Method Example

2. indent(int n)

As name suggests, indent() method adds or removes the white spaces at the beginning of the string for provided n value and adds '\n' at the end of line. This method takes int argument n.

Based on the n value, indentation will be changed.

If n value is positive then it adds n white spaces at beginning.
If n value is negative then removes n white spaces from beginning if white spaces are available.
If n value is 0 then input string remains unchanged.

If input string has line terminations (\n) then it applies to the all lines.

2.1 Syntax

public String indent​(int n)

This is a public method and must be accessed on String instance. Returns new indented String.

2.2 Arguments

n - number of leading white space characters to add or remove

3. Example

We will write a few example programs on indent method for each case of value n.

Consider the following is the input.

String input = "I am Venkatesh";

3.1 n positive value

Passing n value as 5 which is positive. Hence, it adds 5 blank spaces at the beginning of input string.

String output1 = input.indent(5);


In the output, both input and output are printed. Observe 5 white spaces are added and added '\n' at end.

I am Venkatesh
     I am Venkatesh

Now will see length of both values.




input length is 14 and added 5 spaces to output1. Now output1 should be 15 + 5 = 19 but output1 is 20 because it is added with '\n' at end.       

3.2 n negative value

Invoking indent method on above output1 which is already indented by 5 spaces. Now it should remove those 5 spaces.

String output2 = output1.indent(-5);


I am Venkatesh

yes, it has removed all white spaces from beginning and adds '\n' at end.

3.3 n value 0

String output3 = input.indent(0);


I am Venkatesh

Output string unchanged. Not added or removed anything from it.

3.4 Line Terminators

Now assume input string has line terminators such as '\n' or \t. Now intent() method calls internally lines() method on input string. Takes each line from it and apply logic of indent on it. See the below code and it's output.

String lineTerminatorsInput = "Welcome to Java 12 new methods \n 1. indent \n 2.transform \n many";
String lineTerminatorsOutput = lineTerminatorsInput.indent(3);
System.out.println("lineTerminatorsInput : \n"+lineTerminatorsInput);
System.out.println("lineTerminatorsOutput : \n"+lineTerminatorsOutput);


Added 3 white spaces at beginning of each line separator.

lineTerminatorsInput : 
Welcome to Java 12 new methods 
 1. indent 
lineTerminatorsOutput : 
   Welcome to Java 12 new methods 
    1. indent 

4. Internal Implementation

Let us take a look at internal code and it's working mechanism.

public String indent(int n) {
     return isEmpty() ? "" :  indent(n, false);

 private String indent(int n, boolean removeBlanks) {
     Stream stream = removeBlanks ? lines(Integer.MAX_VALUE, Integer.MAX_VALUE)
                                          : lines();
     if (n > 0) {
         final String spaces = " ".repeat(n);
         stream = stream.map(s -> spaces + s);
     } else if (n == Integer.MIN_VALUE) {
         stream = stream.map(s -> s.stripLeading());
     } else if (n < 0) {
         stream = stream.map(s -> s.substring(Math.min(-n, s.indexOfNonWhitespace())));
     return stream.collect(Collectors.joining("\n", "", "\n"));

Step 1: First returns "" if input string is empty by calling isEmpty() method

Step 2: Invokes line() method which returns stream of String, separated by line terminators.

Step 3: if n > 0 then adds n empty spaces by calling repeat() method and adds to all lines.
        if n < 0 then removes n white spaces from beginning.
        if n = 0 then it returns string as unchanged (invoking stripLeading() method.)
        All these are performed on stream of lines and stored as stream.
Step 4: Converts stream to string and returns it.

5. Conclusion

In this short article, We've gone through how to add white left spaces to the string using indent() method. Discussed how to add or remove white spaces and what happen if string has line termination characters.

Example program is implemented in this article is available on GitHub.



About Us

Author: Venkatesh - I love to learn and share the technical stuff.

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,18,Arrays,24,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,8,Collections,37,Collector,1,Command Line,1,Comparator,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,149,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,38,Dictionary,1,Difference,2,Download,1,Eclipse,3,Efficiently,1,Error,1,Errors,1,Exceptions,8,Fast,1,Files,17,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,9,Grant,1,Grep,1,HashMap,2,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,6,Iterate,2,Jackson API,3,Java,32,Java 10,1,Java 11,6,Java 12,5,Java 13,2,Java 14,2,Java 8,128,Java 8 Difference,2,Java 8 Stream Conversions,4,java 8 Stream Examples,12,Java 9,1,Java Conversions,14,Java Design Patterns,1,Java Files,1,Java Program,3,Java Programs,114,Java Spark,1,java.lang,4,java.util. function,1,JavaScript,1,jQuery,1,Kotlin,11,Kotlin Conversions,6,Kotlin Programs,10,Lambda,2,lang,29,Leap Year,1,live updates,1,LocalDate,1,Logging,1,Mac OS,3,Math,1,Matrix,6,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,2,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,31,String,61,String Programs,28,String Revese,1,StringBuilder,1,Swing,1,System,1,Tags,1,Threads,11,Tomcat,1,Tomcat 8,1,Troubleshoot,26,Unix,3,Updates,3,util,5,While Loop,1,
JavaProgramTo.com: Java 12 String API indent​() Method Example
Java 12 String API indent​() Method Example
A Quick Guide to java.lang.String indent​() method introduced in Java 12 version as part of JDK 12. Indent() method indents the string by give number of white spaces at left side or beginning of String.
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content