The method format() formats a String using a format String and arguments. For example, characters ‘s’ and ‘S’ evaluate to “null” if the argument arg is null.

If arg implements Formattable, then the method Formattable, then the method arg.formatTo() is invoked. Otherwise, the result is evaluated by invoking arg.toString().

Here are a few additional specifiers commonly used in Java:

  • %b: Boolean representation.
  • %c: Single character representation.
  • %d: Decimal integer representation.
  • %x: Hexadecimal integer representation.
  • %f: Floating-point numbers (e.g., for formatting doubles).
  • %e: Exponential notation.

For more information on formatting, visit the Javadoc.

Available Signatures

public static String format(String format, Object... args)
public static String format(Locale l, String format, Object... args)

Example

@Test
public void whenFormat_thenCorrect() {
    String value = "Baeldung";
    String formatted = String.format("Welcome to %s!", value);
    assertEquals("Welcome to Baeldung!", formatted);

    boolean boolValue = true;
    String formattedBool = String.format("Boolean: %b", boolValue);
    assertEquals("Boolean: true", formattedBool);

    char charValue = 'A';
    String formattedChar = String.format("Character: %c", charValue);
    assertEquals("Character: A", formattedChar);

    int intValue = 255;
    String formattedInt = String.format("Decimal: %d", intValue);
    assertEquals("Decimal: 255", formattedInt);

    String formattedHex = String.format("Hex: %x", intValue);
    assertEquals("Hex: ff", formattedHex);

    double floatValue = 123.456789;
    String formattedFloat = String.format("Float: %.2f", floatValue);
    assertEquals("Float: 123.46", formattedFloat);

    String formattedExponential = String.format("Exponential: %e", floatValue);
    assertEquals("Exponential: 1.234568e+02", formattedExponential);
}

The String.format() method also allows multiple format specifiers in one go which produces a single string that contains the formatted values:

String multipleFormat = String.format(
  "Boolean: %b, Character: %c, Decimal: %d, Hex: %x, Float: %.2f, Exponential: %e", 
  boolValue, charValue, intValue, intValue, floatValue, floatValue
);

assertEquals("Boolean: true, Character: A, Decimal: 255, Hex: ff, Float: 123.46, Exponential: 1.234568e+02", 
  multipleFormat);

Error Handling and Exceptions

The FormatFlagsConversionMismatchException occurs when incompatible flags are provided for a format specifier. For example, using both %+ and %s (string conversion) together is invalid:

@Test
public void whenIncompatibleFlags_thenFormatFlagsConversionMismatchExceptionThrown() {
    assertThrows(FormatFlagsConversionMismatchException.class, () -> {
        String formatted = String.format("%+s", "Baeldung");
    });
}

While IllegalFormatPrecisionException exception occurs when we attempt to use precision with a format type that doesn’t support it such as integers:

@Test
public void whenInvalidPrecisionForType_thenIllegalFormatPrecisionExceptionThrown() {
    assertThrows(IllegalFormatPrecisionException.class, () -> {
        String formatted = String.format("%.2d", 123);
    });
}

The MissingFormatArgumentException exception is thrown when the number of format specifiers exceeds the number of arguments passed to String.format(). For example, if we provide one format specifier but no corresponding argument:

@Test
public void whenMissingFormatArgument_thenMissingFormatArgumentExceptionThrown() {
    assertThrows(MissingFormatArgumentException.class, () -> {
        String formatted = String.format("Welcome to %s and %s!", "Baeldung");
    });
}

Locale-Based Formatting

Locales define different conventions for separating thousands and decimals:

@Test
public void whenNumberFormatWithLocales_thenCorrect() {
    String frenchFormatted = String.format(Locale.FRANCE, "%,f", 1234567.89);
    assertEquals("1 234 567,890000", frenchFormatted);
    String germanFormatted = String.format(Locale.GERMANY, "%,.2f", 1234567.89);
    assertEquals("1.234.567,89", germanFormatted);
}

Locales influence how dates are presented, with various ordering of day, month, and year:

@Test
public void whenDateFormatWithLocales_thenCorrect() {
    LocalDate date = LocalDate.of(2023, 9, 30);

    DateTimeFormatter usFormatter = DateTimeFormatter.ofPattern("MM/dd/yyyy", Locale.US);
    String usFormatted = date.format(usFormatter);
    assertEquals("09/30/2023", usFormatted);

    DateTimeFormatter germanFormatter = DateTimeFormatter.ofPattern("dd.MM.yyyy", Locale.GERMANY);
    String germanFormatted = date.format(germanFormatter);
    assertEquals("30.09.2023", germanFormatted);
}

Local conventions also impact how currency symbols and values are displayed, with different spacing and punctuation:

@Test
public void whenCurrencyFormatWithLocales_thenCorrect() {
    NumberFormat usCurrencyFormat = NumberFormat.getCurrencyInstance(Locale.US);
    String usFormatted = usCurrencyFormat.format(1000);
    assertEquals("$1,000.00", usFormatted);

    NumberFormat frenchCurrencyFormat = NumberFormat.getCurrencyInstance(Locale.FRANCE);
    String frenchFormatted = frenchCurrencyFormat.format(1000);
    assertEquals("1 000,00 €", frenchFormatted);
}
Next »
Java String.getBytes()
« Previous
Java String.endsWith()
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

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