Formatting output

Usually to print some ouptut you’d use System.out.printl() or System.out.println() method. It’s easy to use but you can face some difficulties in providing output formatted in a specific way.

To format output you can use either of the following methods (they work the same)

  • System.out.format(String format, Object... args)
  • System.out.format(Locale l, String format, Object... args)
  • System.out.printf(String format, Object... args)
  • System.out.printf(Locale l, String format, Object... args)

This is the way how those methods should be used:

%[argIndex$][flags][width][.precision] conversion

where:

  • argIndex – index of the argument passed within the args array
  • flags:
    • – – left justify
    • + – print sign (e.g. +25, -45.7)
    • 0 – pad this argument with zeroes
    • , – use local specific separators (e.g. 124,567,678.877)
    • ( -enclose a negative number in parenthesis
  • width – minimum number of characters to print (nice to keep clean columns)
  • precision – number of digits that will be printed after decimal delimiter (for floating points)
  • conversion:
    • b – boolean
    • c – basic types that represent Unicode characters (char, Character, byte, Byte, short, Short)
    • d – integral types (byte, Byte, short, Short, int, Integer, long, Long, BigInteger)
    • f – floating point (float, Float, double, Double, BigDecimal)
    • s – string (for any argument type)
Previous Post
Next Post