How to use the printf() function in Java

The System.out.printf() function in Java allows users to print formatted data.

Syntax

svg viewer

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

class JavaFormat
{
public static void main(String args[])
{
String data = "Hello World!";
System.out.printf("Printing a string: %s\n", data);
}
}

Note: Using the conversion characters in uppercase will print output in uppercase. Notice the change in the following code.

For instance, %S will be used to print in upper-case instead of %s

class JavaFormat
{
public static void main(String args[])
{
String data = "Hello World!";
System.out.printf("Printing a string in uppercase: %S\n", data);
}
}

2. Printing a decimal integer

class JavaFormat
{
public static void main(String args[])
{
int x = 100;
System.out.printf("Printing a decimal integer: %d\n", x);
}
}

3. Printing a floating point number

class JavaFormat
{
public static void main(String args[])
{
float x = 10.9;
System.out.printf("Printing a floating point number: x = %d\n", x);
}
}

4. Printing current date and time

import java.util.Date;
class JavaFormat
{
public static void main(String args[])
{
Date data = new Date();
System.out.printf("Printing current data and time: %tc", data);
}
}

5. Printing multiple objects

In addition to this, the printf() function permits users to print multiple objects at the same time.

import java.util.Date;
class JavaFormat
{
public static void main(String args[])
{
String data = "Hello World!";
int x = 9876;
Date date = new Date();
System.out.printf("Printing multiple data at once: %S %d %tA \n", data,x,date);
}
}
Copyright ©2024 Educative, Inc. All rights reserved