Java Top

I just announced the new Spring Boot 2 material, coming in REST With Spring:

>> CHECK OUT THE COURSE

1. Overview

In this short tutorial, we’ll see how to pad a String in Java. We’ll focus mainly on a left pad, meaning that we’ll add the leading spaces or zeros to it until it reaches the desired length.

The approach for the right padded String is very similar, so we’ll only point out the differences.

2. Pad a String Using Custom Methods

The String class in Java doesn’t provide a convenient method for padding, so let’s create several methods on our own. First, though, let’s set some expectations:

assertEquals("    123456", padLeftZeros("123456", 10));
assertEquals("0000123456", padLeftZeros("123456", 10));

2.1. Using StringBuilder

We can achieve this with StringBuilder and some procedural logic:

public String padLeftZeros(String inputString, int length) {
    if (inputString.length() >= length) {
        return inputString;
    }
    StringBuilder sb = new StringBuilder();
    while (sb.length() < length - inputString.length()) {
        sb.append('0');
    }
    sb.append(inputString);

    return sb.toString();
}

We can see here that if the original text’s length is equal to or bigger than the desired length, we return the unchanged version of it. Otherwise, we create a new String, starting with spaces, and adding the original one.

Of course, if we wanted to pad with a different character we could just use it instead of a 0.

Likewise, if we want to right pad, we just need to do new StringBuilder(inputString) instead and then add the spaces at the end.

2.2. Using substring

Another way to do the left padding is to create a String with the desired length that contains only pad characters and then use the substring() method:

StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++) {
    sb.append(' ');
}

return sb.substring(inputString.length()) + inputString;

2.3. Using String.format

And, finally, since Java 5, we can use String.format():

return String.format("%1$" + length + "s", inputString).replace(' ', '0');

We should note that by default the padding operation will be performed using spaces. That’s the reason why we need to use the replace() method if we want to pad with zeros or any other character.

For the right pad, we just have to use a different flag: %1$-

3. Pad a String Using Libraries

And, there are external libraries that already offer padding functionalities.

3.1. Apache Commons Lang

Apache Commons Lang provides a package of Java utility classes. One of the most popular ones is the StringUtils.

To use it, we’ll need to include it into our project by adding its dependency to our pom.xml file:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.8.1</version>
</dependency>

And then we pass the inputString and the length, just like the methods we created. We can also pass the padding character:

assertEquals("    123456", StringUtils.leftPad("123456", 10));
assertEquals("0000123456", StringUtils.leftPad("123456", 10, "0"));

Again, the String will be padded with spaces by default or we need to explicitly set another pad character.

There are also corresponding rightPad() methods.

To explore more features of the Apache Commons Lang 3, you can check out our introductory tutorial. If you would like to see other ways of the String manipulation using the StringUtils class, please refer to this article.

3.2. Google Guava

Another library that we can use is Google’s Guava. Of course, we first need to add it to the project by adding its dependency:

<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>27.0-jre</version>
</dependency>

And then use the Strings class:

assertEquals("    123456", Strings.padStart("123456", 10, ' '));
assertEquals("0000123456", Strings.padStart("123456", 10, '0'));

There is no default pad character in this method, so we need to pass it every time.

To right pad, we can use padEnd() method.

The Guava library offers much more features and we have covered a lot of them. You can look here for the Guava related articles.

4. Conclusion

In this quick article, we illustrated how we can pad a String in Java. We presented examples using our own implementations or existing libraries.

As usual, a complete source code can be found over on GitHub.

Java bottom

I just announced the new Spring Boot 2 material, coming in REST With Spring:

>> CHECK OUT THE LESSONS

Leave a Reply

avatar
  Subscribe  
Notify of