Left, Right, or Center Align a String in Java

In Java, we can align a String to the left, right, or center within a specified width by padding the whitespace characters using various methods such as String.format(), StringUtils and a custom function for very specific customizations, if required.

1. Align a String using String.format()

You can use the String.format() method to align a string to the left, right, or center within a specified width. Its first parameter is a format string, and the subsequent parameters are the values that need to be formatted according to the format string.

String formattedString = String.format(format, arg1, arg2, ...);
  • format: contains placeholders (e.g., %s, %d, %f) that indicate where the values should be inserted. The placeholders are replaced by the actual values provided in the subsequent arguments. Format specifiers may include flags for alignment, width, precision, and conversion characters.
  • arg1, arg2, …: These are the values you want to format according to the format string. They are inserted into the placeholders specified in the format string in the order they appear.

For String alignment, the width of the string is specified as a number immediately following the ‘%‘ format specifier.

%[-]widths   //The - flag specifies left alignment

For example, we can align a string “Hello” with total width 10, as follows. To center-align a string, you can calculate the left and right padding and and use it to achieve the center alignment.

String input = "Hello";
int width = 10;
int padding = (width - input.length()) / 2;

String leftAlignedString = String.format("%-" + width + "s", input);
String rightAlignedString = String.format("%" + width + "s", input);
String centeredString = String.format("%" + (padding + input.length()) + "s", input);

2. Align a String using Apache Commons’ StringUtils

Apache Commons Lang library includes the StringUtils class that provides the rightPad(), leftPad(), and center() methods to pad strings for right, left, or center alignment within a specified width. We can use these method to pad the string with empty spaces for alignment purposes.

leftPad(String str, int size)
rightPad(String str, int size)
center(String str, int size)

//Optional pad character in place of empty space. Useful in padding a number with zeros

leftPad(String str, int size, char padChar)
rightPad(String str, int size, char padChar)
center(String str, int size, char padChar)

Using these padding methods is extremely easy and makes code highly readble. Let us rewrite the previous example.

String input = "Hello";
int width = 10;

String leftAlignedString = StringUtils.rightPad(input, width);
String rightAlignedString = StringUtils.leftPad(input, width);
String centeredString = StringUtils.center(input, width);

3. Align a String using Custom Function

We can also create our own custom method as well where can further customize the behavior if needed. I have created a utility class StringAlignUtils, which wraps all the logic inside it and provides convenient methods that you can call directly.

3.1. StringAlignUtils Class

The StringAlignment class extends java.text.Format class. Format is an abstract base class for formatting locale-sensitive information such as dates, messages, and numbers.

StringAlignUtils defines three enum constants for alignment orders.

  • LEFT
  • CENTER
  • RIGHT

The StringAlignUtils also needs a parameter maxChars specifying the length of characters in a single line. If the number of characters in the given String is more than maxChars, the String is split into two Strings.

import java.io.Serial;
import java.text.FieldPosition;
import java.text.Format;
import java.text.ParsePosition;
import java.util.ArrayList;
import java.util.List;

public class StringAlignment extends Format {

  public enum Alignment {
    LEFT, CENTER, RIGHT,
  }

  private final Alignment currentAlignment;
  private final int maxChars;

  public StringAlignment(int maxChars, Alignment align) {
    if (!isValidAlignment(align)) {
      throw new IllegalArgumentException("Invalid justification argument.");
    }
    if (maxChars < 0) {
      throw new IllegalArgumentException("maxChars must be positive.");
    }
    this.currentAlignment = align;
    this.maxChars = maxChars;
  }

  @Override
  public StringBuffer format(Object input, StringBuffer where, FieldPosition ignore) {
    String s = input.toString();
    List<String> strings = splitInputString(s);

    strings.forEach(wanted -> {
      switch (currentAlignment) {
        case RIGHT:
          pad(where, maxChars - wanted.length());
          where.append(wanted);
          break;

        case CENTER:
          int toAdd = maxChars - wanted.length();
          pad(where, toAdd / 2);
          where.append(wanted);
          pad(where, toAdd - toAdd / 2);
          break;

        case LEFT:
          where.append(wanted);
          pad(where, maxChars - wanted.length());
          break;
      }
      where.append("\n");
    });

    return where;
  }

  @Override
  public Object parseObject(String source, ParsePosition pos) {
    return source;
  }

  public String format(String s) {
    return format(s, new StringBuffer(), null).toString();
  }

  private void pad(StringBuffer to, int howMany) {
    to.append(" ".repeat(Math.max(0, howMany)));
  }

  private boolean isValidAlignment(Alignment align) {
    return align == Alignment.LEFT || align == Alignment.CENTER || align == Alignment.RIGHT;
  }

  private List<String> splitInputString(String str) {
    List<String> list = new ArrayList<>();
    if (str == null) return list;
    for (int i = 0; i < str.length(); i += maxChars) {
      int endIndex = Math.min(i + maxChars, str.length());
      list.add(str.substring(i, endIndex));
    }
    return list;
  }
}

3.2. String Left Align Example

Let use use the StringAlign class to left align a String to 50 chracters length.

String input = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt "
    + "ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris "
    + "nisi ut aliquip ex ea commodo consequat.";
int width = 50;

StringAlignment leftAlignment = new StringAlignment(width, StringAlignment.Alignment.LEFT);
String leftAlignedString = leftAlignment.format(input);
System.out.println(leftAlignedString);
left-aligned-text-example-java

3.3. String Right Align Example

Similarily, use StringAlignment class to right align a string padded with empty spaces.

String input = "Lorem ipsum...";  //complete string
int width = 50;

StringAlignment rightAlignment = new StringAlignment(width, Alignment.RIGHT);
String rightAlignedString = rightAlignment.format(input);
System.out.println(rightAlignedString);

Program output.

right-aligned-text-example-java

3.4. String Center Align Example

Finally, use StringAlignment class to center align a string padded with empty spaces.

String input = "Lorem ipsum ...";  //complete string
int width = 50;

StringAlignment centerAlignment = new StringAlignment(width, Alignment.CENTER);
String centerAlignedString = centerAlignment.format(input);
System.out.println(centerAlignedString);

Program output.

center-aligned-text-example-java

Feel free to edit and customize StringAlignment class and its methods as per your needs.

4. Conclusion

This short Java tutorial taught us to align long strings in Java. We learned to align left, right, and center using padded spaces with examples.

For keepign the things simple and readable, the StringUtils’s leftPad(). rightPad() and center() method are the most recommened methods.

Happy Learning !!

Source Code on Github

Comments

Subscribe
Notify of
guest
4 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode