Pad a String in Java



What is string padding?

String padding means adding extra spaces or characters to the string to reach a specified length. This extra character or space can be added before the string, after the string, or on both sides of the string. This is useful for formatting output or aligning text in documents in order to improve the overall appearance of the content. For example, while displaying a table, padding helps to align the content properly so that every column in the lineup is correct.

Approaches to pad a string in Java

There are multiple approaches to pad a string in java. Some of the common methods are ?

  • format()
  • Apache Commons Lang Library
  • repeat()
  • StringBuilder()

1.String.format()

You can use the string.format() method by specifying the format specifier (%Ws), where W is the required width of the string (including the padding) and the string itself.

Syntax

String.format("%-WIDTHs", originalString); // Right padding with spaces
String.format("%WIDTHs", originalString);  // Left padding with spaces

Implementation code

Below is the Java implementation using String.format() for simple padding with spaces.

public class StringPadding {
   public static void main(String[] args) {
      String str = "JAVA";

      // Right padding with spaces
      String paddedRight = String.format("%-15s", str);
      System.out.println("Right Padded: '" + paddedRight + "'");

      // Left padding with spaces
      String paddedLeft = String.format("%15s", str);
      System.out.println("Left Padded: '" + paddedLeft + "'");
   }
}

Output

Right Padded: 'JAVA           '
Left Padded: '           JAVA'

2. Apache Commons Lang library

You can use the Apache Commons Lang library to easily pad strings with spaces or specific characters using the StringUtils class. Before writing the code, we have to install the Apache Commons Lang library on the system.

Setup

Step 1: Go to https://commons.apache.org/lang/download_lang.cgi and download the zip file.

Step 2: Extract and look for the ?commons-lang3-3.17.0 jar file' and copy it into the same file directory in VS Code where you will write the code.

Step 3: Choose this path using the class-path command ?java -cp' in the terminal and run the code.

Syntax

StringUtils.rightPad(originalString, length); // Right padding with spaces
StringUtils.leftPad(originalString, length);   // Left padding with spaces
StringUtils.rightPad(originalString, length, padChar); // Right padding with specific character
StringUtils.leftPad(originalString, length, padChar);   // Left padding with specific character

Implementation code

Below is the Java implementation using the StringUtils class from Apache Commons Lang for flexible padding.

import org.apache.commons.lang3.StringUtils;

public class StringPadding {
   public static void main(String[] args) {
      String str = "Java";

      // Right padding with spaces
      String paddedRight = StringUtils.rightPad(str, 10);
      System.out.println("Right Padded: '" + paddedRight + "'");

      // Left padding with spaces
      String paddedLeft = StringUtils.leftPad(str, 10);
      System.out.println("Left Padded: '" + paddedLeft + "'");

      // Right padding with a specific character
      String paddedRightWithChar = StringUtils.rightPad(str, 10, '*');
      System.out.println("Right Padded with '*': '" + paddedRightWithChar + "'");

      // Left padding with a specific character
      String paddedLeftWithChar = StringUtils.leftPad(str, 10, '*');
      System.out.println("Left Padded with '*': '" + paddedLeftWithChar + "'");
   }
}

Output

Right Padded: 'Java      '
Left Padded: '      Java'
Right Padded with '*': 'Java******'
Left Padded with '*': '******Java'

3. String.repeat()

You can use the String.repeat() method in Java to pad strings with spaces or characters by specifying the length of the padding character inside the parentheses.

Syntax

originalString + " ".repeat(RequiredLength - originalString.length());   // Right padding with spaces
" ".repeat(RequierdLength - originalString.length()) + originalString;    // Left padding with spaces

Implementation code

Below is the Java implementation using String.repeat() to efficiently add padding characters.

public class StringPadding {
   public static void main(String[] args) {
      String str = "Java";

      // Right padding with spaces
      String paddedRight = str + " ".repeat(10 - str.length());
      System.out.println("Right Padded: '" + paddedRight + "'");

      // Left padding with ?*?character
      String paddedLeft = "*".repeat(10 - str.length()) + str;
      System.out.println("Left Padded: '" + paddedLeft + "'");
   }
}

Output

Right Padded: 'Java      '
Left Padded: '******Java'

4. Using String Builder

We can also use StringBuilder to pad a string in Java by appending space or characters to the required string.

Implementation code

Below is the Java implementation using StringBuilder to manually construct padded strings.

public class stbuilder {
   public static void main(String[] args) {
      String str = "Java";

      // Right padding with spaces
      String paddedRight = rightPad(str, 10, ' ');
      System.out.println("Right Padded: '" + paddedRight + "'");

      // Left padding with spaces
      String paddedLeft = leftPad(str, 10, ' ');
      System.out.println("Left Padded: '" + paddedLeft + "'");

      // Right padding with a specific character
      String paddedRightWithChar = rightPad(str, 10, '*');
      System.out.println("Right Padded with '*': '" + paddedRightWithChar + "'");

      // Left padding with a specific character
      String paddedLeftWithChar = leftPad(str, 10, '*');
      System.out.println("Left Padded with '*': '" + paddedLeftWithChar + "'");
   }

   public static String rightPad(String originalString, int length, char padChar) {
      StringBuilder sb = new StringBuilder(originalString);
      while (sb.length() < length) {
         sb.append(padChar);
      }
      return sb.toString();
   }

   public static String leftPad(String originalString, int length, char padChar) {
      StringBuilder sb = new StringBuilder();
      while (sb.length() < length - originalString.length()) {
         sb.append(padChar);
      }
      sb.append(originalString);
      return sb.toString();
   }
}

Output

Right Padded: 'Java      '
Left Padded: '      Java'
Right Padded with '*': 'Java******'
Left Padded with '*': '******Java'
Updated on: 2025-02-27T10:55:09+05:30

61 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements