Right pad a string in Java

Java 8Object Oriented ProgrammingProgramming

To right pad a string, use the String.format and set the spaces.

String.format("%1$-" + 20 + "s", "demotext"));

If you add 30 above, it will display the next string after 30 spaces from the beginning.

String.format("%1$-" + 30 + "s", "demotext")

The following is an example.

Example

 Live Demo

public class Demo {
   public static void main(String []args){
      System.out.print(String.format("%1$-" + 20 + "s", "demotext"));
      System.out.println("Right padded!");
   }
}

Output

demotext Right padded!
raja
Published on 14-Dec-2018 11:43:30
Advertisements