$show=/label

Java 12 String API indent​() Method Example

SHARE:

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);

Output:

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.

System.out.println(input.length());
System.out.println(output1.length());

Output:

14
20

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);

Output:

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);

Output:

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);

Output:

Added 3 white spaces at beginning of each line separator.

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

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.

COMMENTS

BLOGGER

About Us

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

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,16,Arrays,7,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,5,Collections,22,Collector,1,Command Line,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,81,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,4,Dictionary,1,Difference,1,Download,1,Eclipse,2,Efficiently,1,Error,1,Errors,1,Exception,1,Exceptions,3,Fast,1,Files,9,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,4,Grant,1,Grep,1,HashMap,1,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,5,Iterate,2,Jackson API,3,Java,29,Java 10,1,Java 11,5,Java 12,5,Java 13,2,Java 14,2,Java 8,66,Java 8 Difference,2,Java 8 Stream Conversions,2,java 8 Stream Examples,3,Java 9,1,Java Conversions,11,Java Design Patterns,1,Java Files,1,Java Program,2,Java Programs,65,java.lang,5,java.util. function,1,jQuery,1,Kotlin,10,Kotlin Conversions,3,Kotlin Programs,6,Lambda,1,lang,29,Leap Year,1,live updates,1,Logging,1,Mac OS,2,Math,1,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,1,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,21,String,58,String Programs,9,String Revese,1,Swing,1,System,1,Tags,1,Threads,10,Tomcat,1,Tomcat 8,1,Troubleshoot,16,Unix,2,Updates,3,util,5,While Loop,1,
ltr
item
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.
https://1.bp.blogspot.com/-_uXMavDJ8Vk/XOvy3V1O2HI/AAAAAAAABj0/GUe5LP6oYPgeKp-OnWiy6PPA6WCmE1g-gCLcBGAs/s320/Java%2B12%2BString%2Bindent%25E2%2580%258B%2528%2529%2BMethod%2BExample.PNG
https://1.bp.blogspot.com/-_uXMavDJ8Vk/XOvy3V1O2HI/AAAAAAAABj0/GUe5LP6oYPgeKp-OnWiy6PPA6WCmE1g-gCLcBGAs/s72-c/Java%2B12%2BString%2Bindent%25E2%2580%258B%2528%2529%2BMethod%2BExample.PNG
JavaProgramTo.com
https://www.javaprogramto.com/2019/05/java-12-string-indent.html
https://www.javaprogramto.com/
https://www.javaprogramto.com/
https://www.javaprogramto.com/2019/05/java-12-string-indent.html
true
3124782013468838591
UTF-8
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