How to use the printf() function in Java

Parameters

  • Locale – if not null, the object is formatted according to the norms of the specified region

Example

Users in France may choose to print the date according to the local practice which involves the use of comma instead of decimal to represent floating point numbers. The syntax for that will be:

Date data = new Date();
System.out.printf(Locale.FRANCE, "Printing current data and time: %tc", data);

  • Object – the object(s) to be printed on the screen

  • String – the string being passed to the function contains the conversion characters

Conversion characters

In order to simplify the formatting process, Java allows programmers to make use of certain keywords to format different data types.
Some of the commonly used specifiers are:

  • s – formats strings
  • d – formats decimal integers
  • f – formats the floating-point numbers
  • t – formats date/time values

Examples

Look at the following examples to get a better understanding of how the printf() function can be used in different situations.

1. Printing a string