Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

Partner – Microsoft – NPI EA (cat = Baeldung)
announcement - icon

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, visit the documentation page.

You can also ask questions and leave feedback on the Azure Container Apps GitHub page.

Partner – Microsoft – NPI EA (cat= Spring Boot)
announcement - icon

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, you can get started over on the documentation page.

And, you can also ask questions and leave feedback on the Azure Container Apps GitHub page.

Partner – Orkes – NPI EA (cat=Spring)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

Partner – Orkes – NPI EA (tag=Microservices)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – All Access – NPI EA (cat= Spring)
announcement - icon

All Access is finally out, with all of my Spring courses. Learn JUnit is out as well, and Learn Maven is coming fast. And, of course, quite a bit more affordable. Finally.

>> GET THE COURSE
Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – LambdaTest – NPI EA (cat=Testing)
announcement - icon

End-to-end testing is a very useful method to make sure that your application works as intended. This highlights issues in the overall functionality of the software, that the unit and integration test stages may miss.

Playwright is an easy-to-use, but powerful tool that automates end-to-end testing, and supports all modern browsers and platforms.

When coupled with LambdaTest (an AI-powered cloud-based test execution platform) it can be further scaled to run the Playwright scripts in parallel across 3000+ browser and device combinations:

>> Automated End-to-End Testing With Playwright

Course – Spring Sale 2025 – NPI EA (cat= Baeldung)
announcement - icon

Yes, we're now running our Spring Sale. All Courses are 25% off until 26th May, 2025:

>> EXPLORE ACCESS NOW

Course – Spring Sale 2025 – NPI (cat=Baeldung)
announcement - icon

Yes, we're now running our Spring Sale. All Courses are 25% off until 26th May, 2025:

>> EXPLORE ACCESS NOW

1. Overview

In this tutorial, we’ll demonstrate different examples of formatting with the printf() method.

The method is part of the java.io.PrintStream class and provides String formatting similar to the printf() function in C.

Further reading:

Guide to java.util.Formatter

Introduction to formatting Strings in Java using the java.util.Formatter.

Guide to DateTimeFormatter

Learn how to use the Java 8 DateTimeFormatter class to format and parse dates and times

Pad a String with Zeros or Spaces in Java

Learn how to pad a String in Java with a specific character.

2. Syntax

We can use one of these PrintStream methods to format the output:

System.out.printf(format, arguments);
System.out.printf(locale, format, arguments);

We specify the formatting rules using the format parameter. Rules start with the % character.

Let’s look at a quick example before we dive into the details of the various formatting rules:

System.out.printf("Hello %s!%n", "World");

This produces the following output:

Hello World!

As shown above, the format string contains plain text and two formatting rules. The first rule is used to format the string argument. The second rule adds a newline character to the end of the string.

2.1. Format Rules

Let’s have a look at format string more closely. It consists of literals and format specifiers. Format specifiers include flags, width, precision, and conversion characters in this sequence:

%[flags][width][.precision]conversion-character

Specifiers in the brackets are optional.

Internally, printf() uses the java.util.Formatter class to parse the format string and generate the output. Additional format string options can be found in the Formatter Javadoc.

2.2. Conversion Characters

The conversion-character is required and determines how the argument is formatted.

Conversion characters are only valid for certain data types. Here are some common ones:

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

We’ll explore these and a few others later in the tutorial.

2.3. Optional Modifiers

The [flags] define standard ways to modify the output and are most common for formatting integers and floating-point numbers.

The [width] specifies the field width for outputting the argument. It represents the minimum number of characters written to the output.

The [.precision] specifies the number of digits of precision when outputting floating-point values. Additionally, we can use it to define the length of a substring to extract from a String.

3. Line Separator

To break the string into separate lines, we have a %n specifier:

System.out.printf("baeldung%nline%nterminator");

The code snippet above will produce the following output:

baeldung
line
terminator

The %n separator printf() will automatically insert the host system’s native line separator.

4. Boolean Formatting

To format Boolean values, we use the %b format.

According to the docs, it works the following way: if the second argument is null, then the result is “false”. If the argument is a boolean or Boolean, then the result is the string returned by String.valueOf(arg). Otherwise, the result is “true”.

So, if we do the following:

System.out.printf("%b%n", null);
System.out.printf("%B%n", false);
System.out.printf("%B%n", 5.3);
System.out.printf("%b%n", "random text");

then we’ll see:

false
FALSE
TRUE
true

Notice that we can use %B for uppercase formatting.

5. String Formatting

To format a simple string, we’ll use the %s combination. Additionally, we can make the string uppercase:

printf("'%s' %n", "baeldung");
printf("'%S' %n", "baeldung");

And this is the output:

'baeldung' 
'BAELDUNG'

Also, to specify a minimum length, we can specify a width:

printf("'%15s' %n", "baeldung");

which gives us:

'       baeldung'

If we need to left-justify our string, we can use the – flag:

printf("'%-10s' %n", "baeldung");

This is the output:

'baeldung  '

Even more, we can limit the number of characters in our output by specifying a precision:

System.out.printf("%2.2s", "Hi there!");

The first x number in %x.ys syntax is the padding. y is the number of chars.

For our example here, the output is Hi.

6. Char Formatting

The result of %c is a Unicode character:

System.out.printf("%c%n", 's');
System.out.printf("%C%n", 's');

The capital letter C will uppercase the result:

s
S

But if we give it an invalid argument, then Formatter will throw IllegalFormatConversionException.

7. Number Formatting

7.1. Integer Formatting

The printf() method accepts all the integers available in the language — byte, short, int, long, and BigInteger if we use %d:

System.out.printf("simple integer: %d%n", 10000L);

With the help of the d character, we’ll have this result:

simple integer: 10000

In case we need to format our number with the thousands separator, we can use the , flag. And we can also format our results for different locales:

System.out.printf(Locale.US, "%,d %n", 10000);
System.out.printf(Locale.ITALY, "%,d %n", 10000);

As we can see, the formatting in the US is different than in Italy:

10,000 
10.000

7.2. Float and Double Formatting

To format a float number, we’ll need the f format:

System.out.printf("%f%n", 5.1473);

which will output:

5.147300

Of course, the first thing that comes to mind is to control the precision:

System.out.printf("'%5.2f'%n", 5.1473);

Here we define the width of our number as 5, and the length of the decimal part is 2:

' 5.15'

Here we have one-space padding from the beginning of the number to support the predefined width.

To have our output in scientific notation, we just use the e conversion-character:

System.out.printf("'%5.2e'%n", 5.1473);

And this is our result:

'5.15e+00'

8. Date and Time Formatting

For date and time formatting, the conversion string is a sequence of two characters: the t or T character and the conversion suffix.

Let’s explore the most common time and date formatting suffix characters with examples.

Definitely, for more advanced formatting, we can use DateTimeFormatter, which has been available since Java 8.

8.1. Time Formatting

First, let’s see the list of some useful suffix characters for time formatting:

  • H, M, S characters are responsible for extracting the hours, minutes and seconds from the input Date.
  • L, N represent the time in milliseconds and nanoseconds accordingly.
  • p adds a.m./p.m. formatting.
  • z prints out the time-zone offset.

Now, let’s say we want to print out the time part of a Date:

Date date = new Date();
System.out.printf("%tT%n", date);

The code above along with %tT combination produces the following output:

13:51:15

In case we need more detailed formatting, we can call for different time segments:

System.out.printf("hours %tH: minutes %tM: seconds %tS%n", date, date, date);

Having used H, M and S, we get this result:

hours 13: minutes 51: seconds 15

However, listing date multiple times is a pain.

Alternatively, to get rid of multiple arguments, we can use the index reference of our input parameter, which is 1$ in our case:

System.out.printf("%1$tH:%1$tM:%1$tS %1$tp %1$tL %1$tN %1$tz %n", date);

Here we want as an output the current time, a.m./p.m., the time in milliseconds and nanoseconds, and the time-zone offset:

13:51:15 pm 061 061000000 +0400

8.2. Date Formatting

Like time formatting, we have special formatting characters for date formatting:

  • A prints out the full day of the week.
  • d formats a two-digit day of the month.
  • B is for the full month name.
  • m formats a two-digit month.
  • Y outputs a year in four digits.
  • y outputs the last two digits of the year.

Suppose we want to show the day of the week, followed by the month:

System.out.printf("%1$tA, %1$tB %1$tY %n", date);

Then, using A, B and Y, we’d get this output:

Thursday, November 2018

To have our results all in numeric format, we can replace the A, B, Y letters with d, m, y:

System.out.printf("%1$td.%1$tm.%1$ty %n", date);

which will result in:

22.11.18

9. Conclusion

In this article, we discussed how to use the PrintStream#printf method to format output. We looked at the different format patterns used to control the output for common data types.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

Partner – Microsoft – NPI EA (cat = Spring Boot)
announcement - icon

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, visit the documentation page.

You can also ask questions and leave feedback on the Azure Container Apps GitHub page.

Partner – Orkes – NPI EA (cat = Spring)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

Partner – Orkes – NPI EA (tag = Microservices)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Course – Spring Sale 2025 – NPI EA (cat= Baeldung)
announcement - icon

Yes, we're now running our Spring Sale. All Courses are 25% off until 26th May, 2025:

>> EXPLORE ACCESS NOW

Course – Spring Sale 2025 – NPI (All)
announcement - icon

Yes, we're now running our Spring Sale. All Courses are 25% off until 26th May, 2025:

>> EXPLORE ACCESS NOW

eBook Jackson – NPI EA – 3 (cat = Jackson)