How to pad a String in Java?

This article shows you how to use the JDK1.5 String.format() and Apache Common Lang to left or right pad a String in Java.

1. String.format

By default, the String.format() fills extra with spaces \u0020. Normally, we use replace() to pad with other chars, but it will replace the spaces in between the given string.

package com.mkyong;

public class JavaPadString1 {

    public static void main(String[] args) {

        String input = "I Love Java!";

        // I Love Java!
        String result1 = String.format("%s", input);

        // pad 20 chars
        String result2 = String.format("|%20s|", input);    // |        I Love Java!|

        String result3 = String.format("|%-20s|", input);   // |I Love Java!        |

        // ********I*Love*Java!
        String result4 = String.format("%20s", input).replace(" ", "*");

        // I*Love*Java!********
        String result5 = String.format("%-20s", input).replace(" ", "*");





I Love Java!
|        I Love Java!|
|I Love Java!        |

2. Apache Common Lang

To solve the String.format issue above, we can use Apache Common Lang to left, right or center pad a String.



package com.mkyong;

import org.apache.commons.lang3.StringUtils;

public class JavaPadString2 {

    public static void main(String[] args) {

        String input = "I Love Java!";

        String result4 = StringUtils.leftPad(input, 20, "*");

        String result5 = StringUtils.rightPad(input, 20, "*");

        String result6 =, 20, "*");





********I Love Java!
I Love Java!********
****I Love Java!****

If you don’t want to include a library to pad a String, dig into the Apache Common Lang StringUtils.leftPad, and copy the source code 🙂

  public static String leftPad(final String str, final int size, String padStr) {
        if (str == null) {
            return null;
        if (isEmpty(padStr)) {
            padStr = SPACE;
        final int padLen = padStr.length();
        final int strLen = str.length();
        final int pads = size - strLen;
        if (pads <= 0) {
            return str; // returns original String when possible
        if (padLen == 1 && pads <= PAD_LIMIT) {
            return leftPad(str, size, padStr.charAt(0));

        if (pads == padLen) {
            return padStr.concat(str);
        } else if (pads < padLen) {
            return padStr.substring(0, pads).concat(str);
        } else {
            final char[] padding = new char[pads];
            final char[] padChars = padStr.toCharArray();
            for (int i = 0; i < pads; i++) {
                padding[i] = padChars[i % padLen];
            return new String(padding).concat(str);

P.S Above is the source code of StringUtils.leftPad, from Apache Common Lang.


author image


Founder of, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities. Read all published posts by