Table of contents
1.
Introduction
2.
What is the String format() method?
3.
Java String Format Specifiers
4.
Exceptions of Java String format()
4.1.
Java
4.2.
Java
4.3.
Java
4.4.
Java
4.5.
Java
4.6.
Java
5.
Use of Java String format() with locale
5.1.
Java
6.
Frequently Asked Questions
6.1.
What is the use of string format method in Java?
6.2.
What is the alternative to formatting a string in Java?
6.3.
What is the fastest string format in Java?
7.
Conclusion
Last Updated: Sep 27, 2024
Easy

Java String format()

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In Java, strings are objects representing a sequence of character values. An array of characters work the same as a string in Java. The Java String class has a lot of methods to perform operations on strings like compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring(), format(). In this article, we will learn about string format() with the help of code examples. Let us dive into the topic.

What is the String format() method?

The String format() method in java returns a formatted string using the given Locale, specified format string, and arguments. If the Locale is not specified in String.format() method, it uses the default locale by calling the Locale.getDefault() method. In addition to concatenating the strings, we can format the final concatenated string using this method. This format() method of java language is like the sprintf() function in the C Programming language.

Note: The Java Locale class object represents a specific geographic, cultural, or political region. It is a mechanism to for identifying objects, not a container for the objects themselves. A Locale object logically consists of the fields like languages, script, country, variant, extensions.

Syntax: These are two ways in which you can use the string format() method: 

public static String format(Locale loc, String form, Object... args)
public static String format(String form, Object... args)

Parameters: 

  • The locale value to be applied to format()
  • The format of the output.
  • args specifying the number of arguments for the format string.

Return Type: Formatted string. 

There are some exceptions thrown if:
1. If the format is null: NullPointerException
2. If the format is illegal or incompatible: IllegalFormatException

Example 1: Java program to demonstrate the working of format() method

class Ninja {
    public static void main(String args[])
    {
        String str = "Rakesh";
        // Concatenation of two strings
        String s = String.format("My name is %s", str);
        // Output is given upto 8 decimal places
        String str2 = String.format("My internal assessment marks are %.8f", 18.5);
        System.out.println(s);
        System.out.println(str2);
    }
}

Output

My name is Rakesh
My internal assessment marks are 18.50000000

Example 2: Java program to demonstrate concatenation of Arguments to the string using format() method

class Ninja {
    public static void main(String args[])
    {
        String str1 = "Coding";
        String str2 = "Ninjas";
        // %1$ represents first argument
        // %2$ second argument
        String str = String.format("My Company name" + " is: %1$s %2$s", str1, str2);
        System.out.println(str);
    }
}

Output: 

My Company name is: Coding Ninjas

Example 3: Java program to Illustrate Left Padding using format() method

class Ninja {
    public static void main(String args[])
    {
        int num = 1536;
        // The output will be 3 zero's + "1536" in total 7 digits
        String str = String.format("%07d", num);
        System.out.println(str);
    }
}

Output: 

0001536

Must Read Array of Objects in Java

Java String Format Specifiers

Check out this article - C++ String Concatenation.

Exceptions of Java String format()

In Java, the `String.format()` method throws an `IllegalFormatException` if the format string or the arguments passed to it violate certain constraints. 

Let's see some common exceptions that can occur when using `String.format()`:

1. `IllegalFormatConversionException`:

  • This exception is thrown when the format specifier is incompatible with the corresponding argument type.
  • For example, using `%d` to format a string argument or `%s` to format a numeric argument will throw this exception.
  • Example:
  • Java

Java

    String formattedString = String.format("Age: %d", "twenty"); // Throws IllegalFormatConversionException
You can also try this code with Online Java Compiler
Run Code

   

2. `MissingFormatArgumentException`:

  • This exception is thrown when the format string requires more arguments than the ones provided.
  • If a format specifier is present in the format string but no corresponding argument is passed, this exception will be thrown.
  • Example:
  • Java

Java

    String formattedString = String.format("Name: %s, Age: %d", "John"); // Throws MissingFormatArgumentException
You can also try this code with Online Java Compiler
Run Code

    

3. `IllegalFormatPrecisionException`:

  • This exception is thrown when the precision specified in the format string is invalid.
  • Precision is the number of digits to be printed after the decimal point for floating-point numbers or the maximum number of characters to be printed for strings.
  • Example:
  • Java

Java

String formattedString = String.format("Price: %.1f", 19.99); // Valid
String formattedString = String.format("Price: %.f", 19.99); // Throws IllegalFormatPrecisionException
You can also try this code with Online Java Compiler
Run Code


 4. `IllegalFormatWidthException`:

  • This exception is thrown when the width specified in the format string is invalid.
  • Width is the minimum number of characters to be written to the output.
  • Example:
  • Java

Java

String formattedString = String.format("Number: %5d", 123); // Valid
String formattedString = String.format("Number: %-d", 123); // Throws IllegalFormatWidthException
You can also try this code with Online Java Compiler
Run Code


    5. `IllegalFormatFlagsException`:

  • This exception is thrown when the flags specified in the format string are invalid.
  • Flags are additional formatting options, such as left justification (`-`), zero padding (`0`), and more.
  • Example:
  • Java

Java

String formattedString = String.format("Number: %+d", 123); // Valid
String formattedString = String.format("Number: %,d", 123); // Throws IllegalFormatFlagsException
You can also try this code with Online Java Compiler
Run Code


   6. `DuplicateFormatFlagsException`:

  • This exception is thrown when a flag is specified more than once in the format specifier.
  • Example:
  • Java

Java

    String formattedString = String.format("Number: %-+d", 123); // Throws DuplicateFormatFlagsException
You can also try this code with Online Java Compiler
Run Code

Use of Java String format() with locale

In Java, the `String.format()` method can be used with a specific locale to format the string according to the conventions of that locale. The locale represents a specific geographical, political, or cultural region and affects how certain elements, such as numbers, dates, and currencies, are formatted.

When using `String.format()` with a locale, you can ensure that the formatted string adheres to the conventions of the specified locale. This is particularly useful when developing applications that support multiple locales or when formatting output for different regions.

To use `String.format()` with a locale, you can follow these steps:

1. Create a `Locale` object representing the desired locale. You can create a `Locale` object using the `Locale` class constructors or by using the predefined constants available in the `Locale` class.

2. Pass the `Locale` object as the first argument to the `String.format()` method, followed by the format string and the arguments to be formatted.

For example : 

  • Java

Java

import java.util.Locale;

public class LocaleFormatExample {
public static void main(String[] args) {
double amount = 1234.56;

// Format the amount using the default locale
String defaultFormatted = String.format("Amount: %.2f", amount);
System.out.println("Default locale: " + defaultFormatted);

// Format the amount using the US locale
String usFormatted = String.format(Locale.US, "Amount: %.2f", amount);
System.out.println("US locale: " + usFormatted);

// Format the amount using the German locale
String germanFormatted = String.format(Locale.GERMANY, "Amount: %.2f", amount);
System.out.println("German locale: " + germanFormatted);
}
}
You can also try this code with Online Java Compiler
Run Code


Output:

Default locale: Amount: 1234.56
US locale: Amount: 1,234.56
German locale: Amount: 1.234,56

In this example:

  • The `amount` variable holds the value to be formatted.
  • The first `String.format()` call uses the default locale and formats the amount with two decimal places.
  • The second `String.format()` call uses the `Locale.US` locale, which represents the United States. It formats the amount according to the US conventions, with a comma as the thousands separator and a dot as the decimal separator.
  • The third `String.format()` call uses the `Locale.GERMANY` locale, which represents Germany. It formats the amount according to the German conventions, with a dot as the thousands separator and a comma as the decimal separator.

Frequently Asked Questions

What is the use of string format method in Java?

The String.format() method in Java formats a string using specified placeholders and arguments, allowing for customizable, readable output.

What is the alternative to formatting a string in Java?

Alternatives to String.format() in Java include StringBuilder for concatenation and java.text.MessageFormat for localized formatting.

What is the fastest string format in Java?

StringBuilder is generally the fastest for concatenating strings due to its mutable nature, reducing the overhead of creating multiple immutable string objects.

Conclusion

In this article, we have extensively discussed the concept of the string format() method with the help of code examples. Having gone through this article, I am sure you must be excited to read similar blogs. Coding Ninjas has got you covered. Here are some similar blogs to redirect: Converting Java strings to intUnderstanding strings in javaMethod to take input in javaint to string conversion in java  We hope that this blog has helped you enhance your knowledge, and if you wish to learn more, check out our Coding Ninjas Blog site and visit our Library. Here are some courses provided by Coding Ninjas: Basics of C++ with DSACompetitive Programming and MERN Stack Web Development. Do upvote our blog to help other ninjas grow.

Live masterclass