To left, right or center align a string in Java, we pad it with spaces up to a fixed width, adding the spaces after the text for left alignment, before the text for right alignment, and on both sides for center alignment. The JDK does the left and right cases with a width in a String.format() pattern, and a short helper built on String.repeat() does the center case.
We align strings whenever plain text output must line up, such as receipt lines, console reports, log tables and fixed-width file records.
The following example aligns the word Tea inside a 9-character field in all three ways.
String item = "Tea";
String left = String.format("%-9s", item); // "Tea "
String right = String.format("%9s", item); // " Tea"
String middle = center(item, 9); // " Tea "
Notice that the minus flag in %-9s switches the default right alignment to left alignment, and that center() is our own helper from section 1.3. The rest of the post covers the format syntax, long values, Apache Commons StringUtils, a helper that wraps and aligns a whole paragraph, and a printed receipt.
1. Align a String using String.format()
The format specifier %s accepts a width, so %10s means “print the argument in a field of at least 10 characters”. When the text is shorter than the width, Formatter adds spaces on the left. With the – flag, it adds them on the right.

1.1. Left and Right Alignment
The width is a number between % and the conversion character. The same pattern works with System.out.printf() and with String.formatted(), which Java 15 added as an instance method version of String.format().
int width = 12;
String leftAligned = String.format("%-" + width + "s|", "Latte"); // "Latte |"
String rightAligned = String.format("%" + width + "s|", "Latte"); // " Latte|"
String sameResult = "%-12s|".formatted("Latte"); // "Latte |"
Building the pattern with “%-” + width + “s” is the usual trick when the width comes from a variable. The | character in these patterns only marks where the field ends, so we can see the trailing spaces.
The common specifiers for alignment are listed in the table, each applied to the text Cappuccino or to the number 42.
| Specifier | Meaning | Result |
|---|---|---|
| %12s | Right align in 12 characters | ” Cappuccino” |
| %-12s | Left align in 12 characters | “Cappuccino “ |
| %.5s | Keep at most 5 characters | “Cappu” |
| %-8.5s | Cut to 5 and left align in 8 | “Cappu “ |
| %6d | Right align a number in 6 | ” 42″ |
| %06d | Pad a number with zeros | “000042” |
1.2. Long Values and Truncation
The width in %10s is a minimum, so a longer string is printed in full and pushes everything after it to the right. To keep a column fixed, we add a precision such as .10, which cuts the text to at most that many characters.
String full = String.format("%5s|", "Cappuccino"); // "Cappuccino|"
String cut = String.format("%-5.5s|", "Cappuccino"); // "Cappu|"
String noPad = String.format("%05s", "Tea"); // FormatFlagsConversionMismatchException
The last line shows a common mistake. The 0 flag works only for numbers, so Formatter throws FormatFlagsConversionMismatchException for %05s. To pad text with zeros or any other character, we use repeat() as in the next section, or the left padding recipes.
1.3. Center Alignment with repeat()
The format syntax has no flag for centering. We compute the free space, put half of it before the text and the rest after it, and build both runs of spaces with String.repeat(), which exists since Java 11.
static String center(String text, int width) {
int gap = Math.max(0, width - text.length());
int before = gap / 2;
return " ".repeat(before) + text + " ".repeat(gap - before);
}
String even = center("Tea", 9); // " Tea "
String odd = center("Tea", 8); // " Tea "
String tooLong = center("Cappuccino", 6); // "Cappuccino"
We can see that the result always has the full width, because the odd space goes after the text. A popular shortcut pads only the left side with String.format(“%” + (padding + length) + “s”, text), but that result is shorter than the width, so anything printed after it moves. The Math.max() call keeps a string that is longer than the width unchanged, since repeat() throws IllegalArgumentException for a negative count.
2. Align a String using Apache Commons’ StringUtils
The StringUtils class from Apache Commons Lang (commons-lang3 3.21.0) has a method for each of the three alignments. The method names describe where the padding goes, not the alignment, so rightPad() gives left alignment and leftPad() gives right alignment.
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.21.0</version>
</dependency>
String leftSide = StringUtils.rightPad("Tea", 9); // "Tea "
String rightSide = StringUtils.leftPad("Tea", 9, '.'); // "......Tea"
String centered = StringUtils.center("Tea", 9, '*'); // "***Tea***"
String oddCenter = StringUtils.center("Tea", 8); // " Tea "
String nothing = StringUtils.center(null, 9); // null
The optional third argument is the pad character or pad string, and center() puts the extra space on the right the same way as our helper. Every method returns null for a null input instead of throwing NullPointerException. For three methods, adding a library is not worth it in a new project, because String.format() and repeat() cover the same cases.
3. Align a String using Custom Function
Padding a single word takes one call, but a paragraph needs to be split into lines first. A store notice printed on a 24-character display, or a help text in a terminal, has to break between words and align every line on its own.
3.1. The align() Helper
The helper has three parts. An Align enum names the alignment, pad() aligns one line with a switch expression, and wrap() splits the text into lines no longer than the width without cutting words.
enum Align { LEFT, CENTER, RIGHT }
static String pad(String line, int width, Align align) {
int gap = Math.max(0, width - line.length());
return switch (align) {
case LEFT -> line + " ".repeat(gap);
case RIGHT -> " ".repeat(gap) + line;
case CENTER -> " ".repeat(gap / 2) + line + " ".repeat(gap - gap / 2);
};
}
static List<String> wrap(String text, int width) {
List<String> lines = new ArrayList<>();
StringBuilder line = new StringBuilder();
for (String word : text.strip().split("\\s+")) {
if (!line.isEmpty() && line.length() + 1 + word.length() > width) {
lines.add(line.toString());
line.setLength(0);
}
if (!line.isEmpty()) {
line.append(' ');
}
line.append(word);
}
if (!line.isEmpty()) {
lines.add(line.toString());
}
return lines;
}
static String align(String text, int width, Align align) {
return wrap(text, width).stream()
.map(line -> pad(line, width, align))
.collect(Collectors.joining("\n"));
}
A word that is longer than the width gets a line of its own and overflows it, which is safer than cutting a product name or a URL in half.
3.2. Left, Right and Center Examples
The three calls align the same store notice in a 24-character field. Each line in the output is printed between | characters to show the padding.
String note = "Free delivery on orders above 30 dollars. Returns accepted within 14 days.";
String leftNote = align(note, 24, Align.LEFT); // 4 lines, padded on the right
String rightNote = align(note, 24, Align.RIGHT); // 4 lines, padded on the left
String centerNote = align(note, 24, Align.CENTER); // 4 lines, padded on both sides
int lineLength = centerNote.lines().findFirst().orElse("").length(); // 24
LEFT RIGHT CENTER
|Free delivery on orders | | Free delivery on orders| |Free delivery on orders |
|above 30 dollars. | | above 30 dollars.| | above 30 dollars. |
|Returns accepted within | | Returns accepted within| |Returns accepted within |
|14 days. | | 14 days.| | 14 days. |
4. Printing a Receipt with Aligned Text
Many 58 mm thermal receipt printers print 32 characters per line, and a cafe app sends them plain text. The shop name is centered, item names are left aligned and prices are right aligned, so the decimal points line up.
List<String> receipt = List.of(
center("CORNER CAFE", 32),
"-".repeat(32),
String.format(Locale.ROOT, "%-22s%10.2f", "Cappuccino", 3.5),
String.format(Locale.ROOT, "%-22s%10.2f", "Blueberry muffin", 2.75),
String.format(Locale.ROOT, "%-22s%10.2f", "Tea", 1.8),
"-".repeat(32),
String.format(Locale.ROOT, "%-22s%10.2f", "TOTAL", 8.05),
center("Thank you!", 32));
int lines = receipt.size(); // 8
CORNER CAFE
--------------------------------
Cappuccino 3.50
Blueberry muffin 2.75
Tea 1.80
--------------------------------
TOTAL 8.05
Thank you!
Passing Locale.ROOT keeps the dot as the decimal separator on every machine, because String.format() uses the default locale and prints 3,50 on a German system. For tables with several columns and widths computed from the data, the align text in columns tutorial builds a small table printer on top of the same specifiers.
5. String Alignment FAQs
Centering and long values are where most alignment code goes wrong, so the questions start there.
5.1. Is there a center() method in the Java String class?
No. The String class has repeat(), strip() and formatted(), but no method that centers text. We write the three-line center() helper from section 1.3 or call StringUtils.center() when Commons Lang is already on the classpath.
5.2. How do I right align a string with printf()?
We give a width without the minus flag. Right alignment is the default for every conversion, so System.out.printf(“%10s%n”, name) prints name at the right edge of a 10-character field, and %n adds the line separator of the platform.
5.3. Does String.format() cut a string that is longer than the width?
No. The width is a minimum. To cut the value, we add a precision, so %-10.10s always prints 10 characters, either padded or truncated.
5.4. How do I align with dots or another character instead of spaces?
We build the padding with repeat() on that character.
String dots = "Tea" + ".".repeat(9 - "Tea".length()); // "Tea......"
5.5. Why are my columns misaligned with emoji or Chinese text?
The width counts char values (UTF-16 code units), not the columns a terminal draws. An emoji such as a smiley face has a length() of 2, and most Chinese characters take two terminal columns but count as one char. For such text, we need a display-width library or a fixed-width font that treats each symbol as one column.
6. Conclusion
Left and right alignment need nothing more than a width in a format specifier, %-10s or %10s, and a precision such as %-10.10s keeps long values from breaking the layout.
Center alignment needs a small helper that splits the free space, with the odd space after the text so the result keeps its full width. Wrapping a paragraph on word boundaries before padding each line covers notices and help texts, and StringUtils remains an option for projects that already depend on Commons Lang. More String tasks are collected in the Java String tutorial.
7. References
- Formatter Javadoc (Java 25)
- String.repeat() Javadoc
- String.formatted() Javadoc
- StringUtils Javadoc (Commons Lang 3)
Happy Learning !!
I was trying to understand this line,
but I couldn’t figure out why you did that. Then I realized that x – 1/2x = 1/2x so you can just replace it with toAdd / 2.
BTW, in Python, center align is three lines:
That may be true in most situations, but not all.
Did you consider using Java string format APIs. Left and right alignment can be done by using native Java routines.
Yup !! I checked them as well. I wrote this class to get more flexibility e.g. I can mention that after N chars, print text in next line; OR i can align center as well. Also, code is free to modified as per need which provides more freedom. It’s not alternative to native APIs, it’s rather complementing them.