How do I align string print out in left, right, center alignment?

The following code snippet will teach you how to align string in left, right or center alignment when you want to print out string to a console. We will print the string using the printf(String format, Object... args) method. The format specifier / parameter defines how the string will be formatted for output and the args is the value that will be formatted.

The format parameter / specifier include flags, width, precision and conversion-characters in the order shown below. The square brackets in the notation means the part is an optional parameter.

% [flags] [width] [.precision] conversion-character
Flags Description
- left-align the output, when not specified the default is to right-align
+ print (+) or (-) sign for numeric value
0 zero padded a numeric value
, comma grouping separator for number greater that 1000
space will output a (-) symbol for negative value and a space if positive
Conversion Description
s string, use capital S to uppercase the strings
c character, use capital C to uppercase the characters
d integer: byte, short, integer, long
f floating point number: float, double
n new line

Width: Defines the field width for printing out the value of argument. It also represents the minimum number of characters to
be printed out to the output.

Precision: For floating-point conversion the precision define the number of digits of precision in a floating point value. For string value this will extract the substring.

To center the string for output we use the StringUtils.center() method from the Apache Commons Lang library. This method will center-align the string str in a larger string of size using the default space character (‘ ‘). You can supply the third parameter to define your own space character / string.

package org.kodejava.lang;

import org.apache.commons.lang3.StringUtils;

import java.time.LocalDate;
import java.time.Month;
import java.time.temporal.ChronoUnit;

public class StringAlignment {
    private static final Object[][] people = {
            {"Alice", LocalDate.of(2000, Month.JANUARY, 1)},
            {"Bob", LocalDate.of(1989, Month.DECEMBER, 15)},
            {"Carol", LocalDate.of(1992, Month.JULY, 24)},
            {"Ted", LocalDate.of(2006, Month.MARCH, 13)},
    };

    public static void main(String[] args) {
        String nameFormat = "| %1$-20s | ";
        String dateFormat = " %2$tb %2$td, %2$tY  | ";
        String ageFormat = " %3$3s |%n";
        String format = nameFormat.concat(dateFormat).concat(ageFormat);
        String line = new String(new char[48]).replace('\0', '-');

        System.out.println(line);
        System.out.printf("|%s|%s|%s|%n",
                StringUtils.center("Name", 22),
                StringUtils.center("Birth Date", 16),
                StringUtils.center("Age", 6));
        System.out.println(line);

        for (Object[] data : people) {
            System.out.printf(format,
                    data[0], data[1],
                    ChronoUnit.YEARS.between((LocalDate) data[1], LocalDate.now()));
        }

        System.out.println(line);
    }
}

Here is the output of our code snippet above:

------------------------------------------------
|         Name         |   Birth Date   | Age  |
------------------------------------------------
| Alice                |  Jan 01, 2000  |   17 |
| Bob                  |  Dec 15, 1989  |   27 |
| Carol                |  Jul 24, 1992  |   24 |
| Ted                  |  Mar 13, 2006  |   10 |
------------------------------------------------

Maven Dependencies

<!-- https://search.maven.org/remotecontent?filepath=org/apache/commons/commons-lang3/3.12.0/commons-lang3-3.12.0.jar -->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.12.0</version>
</dependency>

Maven Central

How do I escape / display percent sign in printf statement?

You have a problem displaying the % sign when you want to print a number in percentage format using the printf() method. Because the % sign is use as a prefix of format specifiers, you need to escape it if you want to display the % sign as part of the output string.

To escape the percent sign (%) you need to write it twice, like %%. It will print out a single % sign as part of your printf() method output. Let see an example in the code snippet below:

package org.kodejava.lang;

public class EscapePercentSignExample {
    public static void main(String[] args) {
        String format = "The current bank interest rate is %6.2f%%.%n";
        System.out.printf(format, 10f);
    }
}

In the code snippet above we use the following format %6.2f%%.%n which can be explained as:

  • %6.2f format the number (10f) as six characters in width, right justified, with two places after decimal point. The f conversion character means it accept a float value.
  • %% will escape the % sign and print it as part of the output.
  • %n will print out a new line character.

When you execute the code, it will print:

The current bank interest rate is  10.00%.

How do I display negative number in parentheses?

The code snippet below show us how to display or format negative number in parentheses. We start by defining the number format, the pattern has two parts separated by a semicolon. In the snippet we use the #,##0.00;(#,##0.00) pattern. The pattern after the semicolon will be used to format negative number.

Next we create an instance of DecimalFormat by calling getInstance() method. We apply the format pattern for the formatter object by calling the applyPattern() method of the DecimalFormat instance. To format the number we simply call the format() method and pass the number we are going to format for display or print out.

package org.kodejava.text;

import java.text.DecimalFormat;

public class NegativeNumberFormat {
    // Pattern for formatting negative number.
    public static final String PATTERN1 = "#,##0.00;(#,##0.00)";
    public static final String PATTERN2 = "$#,##0.00;-$#,##0.00";

    public static void main(String[] args) {
        DecimalFormat df = (DecimalFormat) DecimalFormat.getInstance();
        df.applyPattern(PATTERN1);

        // Format using parentheses
        System.out.println("Positive: " + df.format(125));
        System.out.println("Negative: " + df.format(-125));

        // Format using currency symbol and minus sign
        df.applyPattern(PATTERN2);
        System.out.println("Positive: " + df.format(1000));
        System.out.println("Negative: " + df.format(-1000));
    }
}

The result of the code snippet above is:

Positive: 125.00
Negative: (125.00)
Positive: $1,000.00
Negative: -$1,000.00

If you need to parse negative numbers in parentheses to produce the represented number you can see the following example How do I parse negative number in parentheses?.

How do I add leading zeros to a number?

This example shows you how to use the String.format() method to add zero padding to a number. If you just want to print out the result you can use System.out.format(). This method is available since Java 1.5, so If you use a previous version you can use the NumberFormat class, see: How do I format a number with leading zeros?.

package org.kodejava.lang;

public class LeadingZerosExample {
    public static void main(String[] args) {
        int number = 1500;

        // String format below will add leading zeros (the %0 syntax)
        // to the number above. The length of the formatted string will
        // be 7 characters.
        String formatted = String.format("%07d", number);

        System.out.println("Number with leading zeros: " + formatted);
    }
}

Here is the result of the code snippet above:

Number with leading zeros: 0001500

For more information about the format syntax you can find it here.

How do I format a date into dd/MM/yyyy?

Formatting how data should be displayed on the screen is a common requirement when creating a program or application. Displaying information in a good and concise format can be an added values to the users of the application. In the following code snippet we will learn how to format a date into a certain display format.

For these purposes we can utilize the DateFormat and SimpleDateFormat classes from the java.text package. We can easily format a date in our program by creating an instance of SimpleDateFormat class and specify to format pattern. Calling the DateFormat.format(Date date) method will format a date into a date-time string.

You can see the details about date and time patters in the following link: Date and Time Patterns. Now, let’s see an example as shown in the code snippet below.

package org.kodejava.text;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateFormatExample {
    public static void main(String[] args) {
        Date date = Calendar.getInstance().getTime();

        // Display a date in day, month, year format
        DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
        String today = formatter.format(date);
        System.out.println("Today : " + today);

        // Display date with day name in a short format
        formatter = new SimpleDateFormat("EEE, dd/MM/yyyy");
        today = formatter.format(date);
        System.out.println("Today : " + today);

        // Display date with a short day and month name
        formatter = new SimpleDateFormat("EEE, dd MMM yyyy");
        today = formatter.format(date);
        System.out.println("Today : " + today);

        // Formatting date with full day and month name and show time up to
        // milliseconds with AM/PM
        formatter = new SimpleDateFormat("EEEE, dd MMMM yyyy, hh:mm:ss.SSS a");
        today = formatter.format(date);
        System.out.println("Today : " + today);
    }
}

Let’s view what we got on the console:

Today : 24/09/2021
Today : Fri, 24/09/2021
Today : Fri, 24 Sep 2021
Today : Friday, 24 September 2021, 09:36:32.724 AM