What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.

Java’s standard String API has no general-purpose pad() method. For Java 11 and later, use a small helper built with String.repeat() when you need arbitrary padding characters; use String.format() or printf for presentation and numeric formatting. Third-party options such as Apache Commons Lang and Guava are useful when those libraries are already dependencies.

What “padding” means in Java

Padding adds characters before or after a value until it reaches a target minimum width:

  • Left padding: characters go before the value, such as " Java".
  • Right padding: characters go after it, such as "Java ".

The usual calculation is paddingNeeded = targetWidth - value.length(). If the value already meets or exceeds the target, a padding operation should return it unchanged rather than truncate it. In Java, length() counts UTF-16 code units, not necessarily visible characters or terminal columns.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use String.format() for formatted output

String.format() is concise for spaces, aligned report columns, and numeric output. Its field width is a minimum, not a maximum.

String rightAligned = String.format("%10s", "Java");
String leftAligned  = String.format("%-10s", "Java");

System.out.println(rightAligned); // "      Java"
System.out.println(leftAligned);  // "Java      "

String unchanged = String.format("%5s", "Programming");
// "Programming"

The - flag left-justifies a value; without it, text is right-justified. Formatter syntax and field-width rules are documented in java.util.Formatter.

Zero-padding numbers

For numbers, use numeric conversion rather than treating the number as ordinary text:

String decimal = String.format("%05d", 42);       // "00042"
String hex     = String.format("%08x", 255);       // "000000ff"
String longVal = String.format("%010d", 123456L);  // "0000123456"

Zero-padding changes presentation only. "00042" is still a textual representation of the number 42; parsing it produces the same numeric value.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Dynamic widths

Java’s formatter does not use C’s * width syntax. Build the format string when the width is variable:

String right = String.format("%" + width + "s", value);
String left  = String.format("%-" + width + "s", value);
String zeros = String.format("%0" + width + "d", number);

Validate widths supplied by users or other untrusted sources. Invalid format strings can throw IllegalFormatException, and unreasonable widths can cause unnecessary allocation.

Dependency-free padding with String.repeat()

String.repeat(int) is available from Java 11 onward. It repeats a string and rejects a negative repeat count, so calculate the missing width and guard it first. The API is documented at the Java SE String.repeat reference.

public final class Padding {
    private Padding() {
    }

    public static String leftPad(String value, int width, char padChar) {
        if (value == null) {
            return null;
        }

        int missing = width - value.length();
        return missing <= 0
                ? value
                : String.valueOf(padChar).repeat(missing) + value;
    }

    public static String rightPad(String value, int width, char padChar) {
        if (value == null) {
            return null;
        }

        int missing = width - value.length();
        return missing <= 0
                ? value
                : value + String.valueOf(padChar).repeat(missing);
    }
}
Padding.leftPad("7", 3, '0');      // "007"
Padding.rightPad("Java", 8, '.');  // "Java...."
Padding.leftPad("abcdef", 3, '0'); // "abcdef"
Padding.leftPad("", 4, '0');       // "0000"
Padding.leftPad("Java", -1, '0');  // "Java"

The example deliberately preserves null. Other valid policies are to reject it, treat it as empty, or render the literal text "null"; choose one explicitly for your application.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Repeating a multi-character pad token

When the pad is a string such as "yz", repeat it until the required width is filled, then truncate only the final token if necessary:

static String leftPad(String value, int width, String padString) {
    if (value == null) return null;
    if (padString == null || padString.isEmpty()) {
        throw new IllegalArgumentException("padString must not be empty");
    }

    int missing = width - value.length();
    if (missing <= 0) return value;

    StringBuilder padding = new StringBuilder(missing);
    while (padding.length() < missing) {
        padding.append(padString);
    }
    padding.setLength(missing);
    return padding + value;
}

leftPad("cat", 8, "yz"); // "yzyzycat"

Before Java 11: use StringBuilder

On Java versions without String.repeat(), construct the padding directly:

static String leftPad(String value, int width, char padChar) {
    if (value == null) return null;

    int missing = width - value.length();
    if (missing <= 0) return value;

    StringBuilder result = new StringBuilder(width);
    for (int i = 0; i < missing; i++) {
        result.append(padChar);
    }
    return result.append(value).toString();
}

Library alternatives

Apache Commons Lang

If Commons Lang is already in the project, StringUtils handles left, right, and multi-character padding:

import org.apache.commons.lang3.StringUtils;

String a = StringUtils.leftPad("bat", 5, 'z');   // "zzbat"
String b = StringUtils.rightPad("bat", 5, 'z');  // "batzz"
String c = StringUtils.leftPad("bat", 8, "yz");  // "yzyzybat"

Its documented behavior returns null for a null input, leaves values at least the target size unchanged, and truncates a repeated multi-character token to the required length. See the latest API documentation and source implementation. Adding a dependency solely for a three-line helper is usually unnecessary.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Guava

Guava provides single-character left padding:

import com.google.common.base.Strings;

String result = Strings.padStart("7", 3, '0'); // "007"

Strings.padStart returns the original value when the requested minimum is nonpositive or already met. It is most sensible when Guava is already part of the application. See the Guava API reference.

Nulls, empty values, and invalid widths

  • Null: a manual helper that calls value.length() throws NullPointerException unless it checks first. Commons Lang preserves null; String.format("%s", null) commonly produces the literal text "null".
  • Empty string: it is a valid value distinct from null; padding "" to width four produces four pad characters.
  • Zero or negative width: return the original value when its current length already meets the requested width.
  • Very large width: may allocate a very large string. Apply a sensible maximum when the width is externally controlled.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Unicode, display columns, and byte widths

String.length() counts UTF-16 code units. A supplementary character such as an emoji can use a surrogate pair; combining marks, East Asian characters, and emoji sequences can also occupy a different number of terminal columns than their Java length suggests. Therefore, ordinary formatter widths are not reliable visual alignment for arbitrary international text.

For machine-readable fixed-width data, define what “width” means: UTF-16 units, Unicode code points, grapheme clusters, encoded bytes, or terminal display columns. Commons Lang specifically distinguishes character repetition from string repetition and documents limitations involving supplementary Unicode characters.

Byte-oriented protocols require an explicit charset:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
import java.nio.charset.StandardCharsets;

int byteLength = value.getBytes(StandardCharsets.UTF_8).length;

Appending characters until String.length() reaches a number does not guarantee a particular UTF-8 byte count. A byte-width implementation must specify the charset, padding byte, overflow behavior, and whether truncation may split a multibyte character.

Formatting, serialization, and performance choices

Requirement Best first choice Reason
Align text in a report String.format() or printf Readable field-width syntax
Zero-pad an integer String.format("%05d", number) Expresses numeric intent
Arbitrary single character String.repeat() helper Dependency-free and explicit
Repeating multi-character token Custom helper or Commons Lang Handles a partial final token
Existing Commons Lang project StringUtils.leftPad/rightPad Mature utility API
Existing Guava project Strings.padStart Simple single-character left padding
Null preservation Custom helper or Commons Lang Avoids accidental "null"
Fixed byte-width output Encoding-aware code Character length is insufficient

String.format() performs general format parsing and can be locale-sensitive for some numeric conversions, so it is best suited to presentation. A specialized helper may be clearer in a hot path, but benchmark the actual workload and Java version before changing code. Strings are immutable, so any operation that adds padding creates a new string.

Common mistakes

  • Using %05s for text zero-padding: the zero flag is intended for numeric conversions, not arbitrary string padding.
  • Assuming width truncates: formatter width normally preserves values longer than the field.
  • Confusing padding with truncation: cutting an overlong value is a separate policy that must be explicit.
  • Formatting data for serialization: presentation formatting can vary by locale; define a stable machine format instead.
  • Ignoring Unicode width: equal Java lengths do not guarantee equal visual or byte widths.
  • Adding a dependency for one helper: use Commons Lang or Guava when their broader utility set is already justified.

Test the behavior you actually need

import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;

class PaddingTest {
    @Test void padsOnTheLeft() {
        assertEquals("00042", Padding.leftPad("42", 5, '0'));
    }

    @Test void padsOnTheRight() {
        assertEquals("Java....", Padding.rightPad("Java", 8, '.'));
    }

    @Test void doesNotTruncateLongerValues() {
        assertEquals("abcdef", Padding.leftPad("abcdef", 3, '0'));
    }

    @Test void handlesEmptyString() {
        assertEquals("0000", Padding.leftPad("", 4, '0'));
    }

    @Test void preservesNullAccordingToPolicy() {
        assertNull(Padding.leftPad(null, 4, '0'));
    }

    @Test void handlesZeroAndNegativeWidths() {
        assertEquals("Java", Padding.leftPad("Java", 0, '0'));
        assertEquals("Java", Padding.leftPad("Java", -1, '0'));
    }
}

Also test an exact-width value, a multi-character token that does not divide evenly, supplementary Unicode text, externally supplied extreme widths, and locale-sensitive formatting where applicable.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.