Formatting with printf() in Java

Introduction:

In this article, we will look at formatting with printf() in Java. Java printf method is used to print a formatted string on the console. We can pass format specifiers and based on these specifiers, it formats the string. In this post, we will learn how System.out.printf() works and will look at few Java printf example.

 

1. Java Printf() Syntax:

Following is the syntax of Java printf method:

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

The format argument is used to specify the formatting of the string. We use the last parameter for passing the arguments used with the format. If we don’t provide any format specifier in the format string, it does not require the arguments. Also, if the arguments are more than the count of format specifiers, it will ignore all extra arguments.

We can also provide one Local parameter. This is used to do the formatting according to the Locale. Let me show you one simple example of how it works:

public class Example {
    public static void main(String[] args) {
        System.out.printf("%s = %d", "Ten", 10, 11);
    }
}

If we execute this program, it will print the below output :

Ten = 10

We are using two format specifiers in this example: %s and %d. %s used for a string and %d used for a signed decimal integer.

We are also passing three arguments. The first and second arguments, i.e. “Ten” and 10 are used with the format string but the third argument is ignored because we have only two format specifiers. IDEs like IntelliJ IDEA will show one compile-time message like “too many arguments for format string”.

 

2. Syntax of Format Specifier:

Below is the syntax of format specifier:

%<argument_index$><flags><width><.precision>conversion

conversion:

Following are the conversion characters we can use with printf:

  • c – character. C will print the character in uppercase.
  • d– base 10 decimal numbers
  • f– floating-point numbers
  • s– strings. ‘S’ will print the string in uppercase.
  • o– octal numbers
  • i– base 10 integers
  • u– unsigned decimal numbers
  • x,X– hexadecimal numbers
  • n– for printing a new line
  • h,H– Hexadecimal for integers and hash code for other objects
  • e,E– Scientific notation, floating-point numbers
  • a,A– Hexadecimal floating point
  • %– To print the character ‘%’
  • g,G– floating-point or scientific notation, whichever is shorter. i.e. it will take either %f or %e.
  • %t,%T– time and date.

 

2.1. argument_index:

This can refer to one argument using its index. We can pass multiple arguments as described above. %n$ can access the argument at position ‘n’. For example:

public class Example {
    public static void main(String[] args) {
        System.out.printf("%1$d,%3$d,%2$d,%4$d", 1, 2, 3, 4);
    }
}

It will print the below output:

1,3,2,4

2.2. flags:

Following are the supported flags:

  • +‘ : Used for floating-point and integral values. It prefixes one ‘+‘ sign to the result.
  • ' ': Prefix one blank space on positive results. This is valid only for floating-point and integral values.
  • 0‘: Pad leading zeros to the result to match the provided ‘width’.
  • #‘: If we use it with octal conversion, it prefixes the output with ‘0’. And, if we use it with hexadecimal conversion, it prefixes the output with ‘0x‘.
  • (‘: This is used to enclose negative numbers in parentheses.
  • ,‘: It will include locale-specific separators to a numbers.

 

2.3. width:

‘width’ value is used to define the minimum number of characters the output should have. If the output length is less than the ‘width‘ value, it adds extra spaces.

 

2.4. precision:

precision‘ value is used to define the maximum number of characters the output should have. If the output length is more than ‘precision‘, it will right truncate the extra characters. For floating-point values, it is mathematical precision.

 

2.5. Examples of flag, width, and precision:

The below example uses distinct combinations of flag, width, and precisions:

public class Example {
    public static void main(String[] args) {
        System.out.printf("Example1:(%-5d)\n", 10);
        System.out.printf("Example2:(%+d)\n", 20);
        System.out.printf("Example3:(% d)\n", 30);
        System.out.printf("Example4:(%#o)\n", 10);
        System.out.printf("Example5:(%#X)\n", 10);
        System.out.printf("Example6:%(d\n", -40);
        System.out.printf("Example7:%,d\n", 1234567);
        System.out.printf("Example8:(%5d)\n", 123);
        System.out.printf("Example9:%.2f\n", 123.45678);
        System.out.printf("Example10:%.2s\n", "hello");
    }
}

It will print the below output:

Example1:(10   )
Example2:(+20)
Example3:( 30)
Example4:(012)
Example5:(0XA)
Example6:(40)
Example7:1,234,567
Example8:(  123)
Example9:123.46
Example10:he

Explanation:

I have shown nine examples, with different outputs produced by each. Following are the meanings of each of these printf statements:

  • Example1: Here, ‘flag‘ is ‘-‘ and ‘width‘ is ‘5’. It is printing integer ’10’ i.e. a two-digit number. So, it adds three more spaces to the end, and the output is left justified.
  • Example2: ‘flag’ is ‘+‘ and we are printing integer ’20’. It adds ‘+’ to the left. For negative numbers, it will change nothing.
  • Example3: ‘flag’ is ' ' and we are printing integer ‘30‘. It adds one blank space to the left.
  • Example4: ‘flag’ is ‘#‘ and it is printing the octal value of ’10’. The octal of ’10’ is ’12’ and because of the flag, it adds one ‘0’ to the left.
  • Example5: This is like the above example. But we are printing the hexadecimal value of ’10’, which is ‘A’ (we are using ‘%X‘ here. For ‘%x‘, it will be ‘a’). Because of the ‘flag’ ‘#‘, it adds one ‘0X‘ to the start.
  • Example6: The flag is ‘(‘ and we are printing negative numbers. It enclosed it in a parenthesis.
  • Example7: the flag is ‘,‘ and we are printing one integer. The output adds separator to the provided number. This output may differ based on the current local defined in the system.
  • Example8: We don’t have any flag here. We are only using one width of value ‘5‘ and we are printing the number ‘123’. Since the width is ‘5‘ and the size of the number is ‘3‘, it adds two spaces to the left to make it equal to the width.
  • Example9: Here, precision is ‘2‘ for the floating-point conversion. It formats the value with precision ‘2‘.
  • Example10: This example also uses only precision ‘2‘ but for string conversion. It keeps only two characters, and right truncates the other characters.

 

3. Boolean Formatting Using Printf

"%b" is used for boolean formatting. The following are examples of boolean formatting. '%B' used to print the result in capital letters:

public class Example {
    public static void main(String[] args) {
        System.out.printf("Example1:%b\n", 10);
        System.out.printf("Example2:%B\n", 10);
        System.out.printf("Example3:%b\n", true);
        System.out.printf("Example4:%b\n", false);
        System.out.printf("Example5:%b\n", "true");
        System.out.printf("Example6:%b\n", "false");
        System.out.printf("Example7:%b\n", 0);
        System.out.printf("Example8:%b\n", -0);
    }
}

It will give the below output:

Example1:true
Example2:TRUE
Example3:true
Example4:false
Example5:true
Example6:true
Example7:true
Example8:true

 

4. Time Formatting Using Printf

Following are the suffix we can use to format a time value:

  • H – Hour of the day formatting in 24 hours. It is a two-digit value starting from 00 to 23.
  • k– It is used to format hours in 24 hours. The only difference between H and k is that it doesn’t add one leading zero like H.
  • I – This is also “hour of the day” formatting in 12 hours.
  • l – Hour of the day formatting in 12 hours. It doesn’t add leading zero.
  • M – Minutes in an hour. Values are between 00 to 59
  • S – Seconds in a minute. Values are between 00 to 59
  • L, N – L is for three-digit milliseconds and N is for nine-digit nanoseconds.
  • p, T – Time string in lowercase (p) or uppercase (T)
  • z, Z – Numeric, or abbreviation time-zone.
  • s, Q – Unix seconds and milliseconds.

 

4.1. Example of Time Formatting

import java.util.Date;

public class Example {
    public static void main(String[] args) {
        Date curerntDate = new Date();

        System.out.printf("%tH:%tl:%tM:%tS:%tL:%tZ", curerntDate, curerntDate, curerntDate, curerntDate, curerntDate, curerntDate);
    }
}

It will print one output something like below:

22:10:45:16:026:IST

 

5. Date Formatting Using Printf

Following suffix used for date formatting:

  • A, a – Full and abbreviated day of week
  • Y,y – Four digits and two digits of the year
  • j – Day of the year in three digits.
  • e – the day of the month in 1 to 31
  • d – the day of the month in two digits always
  • m – two-digit month number
  • D – month/day/year
  • F – year-month-day
  • c – human readable date and time

Let’s look at the below example:

import java.util.Date;

public class Example {
    public static void main(String[] args) {
        Date curerntDate = new Date();

        System.out.printf("Month : %tB\n",curerntDate);
        System.out.printf("Day : %tA\n",curerntDate);
        System.out.printf("Year : %tY\n",curerntDate);
    }
}

Output:

Month : May
Day : Thursday
Year : 2020

 

6. Number formatting using print

Let’s consider the below example that uses different number formatters:

public class ExampleProgram {
    public static void main(String[] args) {
        System.out.printf("Example 1 : %d\\n", 10);
        System.out.printf("Example 2 : %f\\n", 4.3);
        System.out.printf("Example 3 : %.2f\\n", 4.39987);
        System.out.printf("Example 4 : %o\\n", 40);
        System.out.printf("Example 5 : %x\\n", 40);
        System.out.printf("Example 6 : %h\\n", 40098);
        System.out.printf("Example 7 : %e\\n", 34.567998);
        System.out.printf("Example 8 : %a\\n", 40.5678);
    }
}

It will print the below output :

Example 1 : 10
Example 2 : 4.300000
Example 3 : 4.40
Example 4 : 50
Example 5 : 28
Example 6 : 9ca2
Example 7 : 3.456800e+01
Example 8 : 0x1.448adab9f559bp5

It formats the numbers as we have defined above. All examples are straightforward. Only Example 3 formats the floating-point number up to two decimal places.

 

6. Difference between String.format() and System.out.printf()

String.format() can format a string similar to System.out.printf(). The only difference between these two is that String.format() formats the string and returns this value but System.out.printf() formats and prints that value. The outputs are the same, but both work differently.

 

Summary: 

In this post, we looked at formatting with printf() in Java. We discussed Java System.out.printf() method and distinct use cases.  It comes in handy to create a formatted string. Using the format specifiers, you can convert it to different strings and assign them to other variables.