Close Menu
MKOVAH Magazine
    Facebook X (Twitter) Instagram
    MKOVAH Magazine
    • Home
    • Technology
    • Digital World
    • Business
    • Automotive
    MKOVAH Magazine
    Home»Blogs»Formatting Strings in Java: String.format() Method
    Blogs

    Formatting Strings in Java: String.format() Method

    TiagoBy TiagoSeptember 12, 202612 Mins Read
    Share Facebook Twitter Pinterest LinkedIn WhatsApp Reddit Tumblr Email
    String.format() Method in Java: Syntax and Examples
    Share
    Facebook Twitter LinkedIn Pinterest Email

    String.format() Method in Java creates formatted strings by inserting values into placeholders and controlling how text, numbers, dates, and other data appear. It is particularly useful when applications need readable messages, reports, tables, prices, percentages, dates, or dynamically generated output.

    Instead of joining multiple values with repeated + operators, developers can create a format pattern and supply the required arguments. This approach produces cleaner, more consistent, and easier-to-maintain Java code.

    What Is the String.format() Method in Java?

    String.format() is a static method of Java’s String class. It accepts a format string and one or more arguments, applies the requested formatting rules, and returns a new string.

    The original values are not modified. The method simply creates a formatted representation of them.

    Consider this basic example:

    String name = "Daniel";
    int age = 28;
    
    String message = String.format(
        "My name is %s and I am %d years old.",
        name,
        age
    );
    
    System.out.println(message);

    Output:

    My name is Daniel and I am 28 years old.

    In this example:

    • %s represents a string.
    • %d represents a decimal integer.
    • name replaces %s.
    • age replaces %d.

    String.format() Method Syntax

    Java provides two commonly used versions of the method.

    Default Locale Syntax

    String.format(String format, Object... args)

    This version uses the system’s default locale.

    Read More: Java Records in Java 16: Syntax, Features, and Examples

    Custom Locale Syntax

    String.format(Locale locale, String format, Object... args)

    This version lets developers control language-sensitive formatting for numbers and other values.

    Example:

    String result = String.format(
        Locale.US,
        "Price: $%,.2f",
        12500.75
    );
    
    System.out.println(result);

    Output:

    Price: $12,500.75

    Parameters and Return Value

    The String.format() method uses the following parameters:

    • format: The string containing normal text and format specifiers.
    • args: The values inserted into the format specifiers.
    • locale: An optional locale that controls regional formatting conventions.

    The method returns a new formatted String.

    String product = "Keyboard";
    double price = 49.99;
    
    String details = String.format(
        "Product: %s | Price: $%.2f",
        product,
        price
    );

    The variable details stores:

    Product: Keyboard | Price: $49.99

    Understanding Java Format Specifiers

    A format specifier tells Java how an argument should be displayed. It begins with a percent sign and normally ends with a conversion character.

    Its general structure is:

    %[argument_index$][flags][width][.precision]conversion

    Not every section is required. A simple format specifier may contain only % and a conversion character.

    For example:

    String.format("%s", "Java");

    Here, %s instructs Java to represent the argument as a string.

    Common String.format() Specifiers

    SpecifierPurposeExample value
    %sString or general object"Java"
    %dDecimal integer150
    %fFloating-point number19.95
    %bBoolean valuetrue
    %cCharacter'A'
    %xHexadecimal integer255
    %oOctal integer64
    %eScientific notation1250.5
    %hHash codeAn object
    %nPlatform-specific line breakNo argument
    %%Literal percent signNo argument

    Formatting Strings With %s

    The %s specifier converts an argument into its string representation.

    String language = "Java";
    String result = String.format(
        "Programming language: %s",
        language
    );
    
    System.out.println(result);

    Output:

    Programming language: Java

    Objects can also be supplied to %s. Java typically uses the object’s toString() method to produce the formatted value.

    String result = String.format(
        "Current user: %s",
        user
    );

    Converting Text to Uppercase

    Using %S instead of %s converts the formatted text to uppercase.

    String result = String.format(
        "Language: %S",
        "Java"
    );
    
    System.out.println(result);

    Output:

    Language: JAVA

    Formatting Integers With %d

    The %d specifier formats whole numbers in decimal form.

    int quantity = 25;
    
    String result = String.format(
        "Available quantity: %d",
        quantity
    );
    
    System.out.println(result);

    Output:

    Available quantity: 25

    Adding Thousands Separators

    The comma flag adds grouping separators according to the selected locale.

    int population = 1500000;
    
    String result = String.format(
        "%,d",
        population
    );
    
    System.out.println(result);

    With a US-style locale, the output is:

    1,500,000

    Adding Leading Zeros

    A number can be padded with leading zeros by specifying a width and using the 0 flag.

    int orderNumber = 42;
    
    String result = String.format(
        "%06d",
        orderNumber
    );
    
    System.out.println(result);

    Output:

    000042

    The complete formatted value occupies six character positions.

    Formatting Decimal Numbers With %f

    The %f specifier formats floating-point values.

    double value = 45.6789;
    
    String result = String.format(
        "%f",
        value
    );
    
    System.out.println(result);

    Output:

    45.678900

    By default, %f displays six digits after the decimal point.

    Controlling Decimal Places

    Precision can be defined after a period.

    double price = 45.6789;
    
    String result = String.format(
        "%.2f",
        price
    );
    
    System.out.println(result);

    Output:

    45.68

    Java rounds the number to two decimal places.

    Formatting Currency Values

    double price = 1299.5;
    
    String result = String.format(
        Locale.US,
        "Total: $%,.2f",
        price
    );
    
    System.out.println(result);

    Output:

    Total: $1,299.50

    This pattern includes a thousands separator and always displays two decimal places.

    Formatting Percentages

    A percentage can be created by multiplying a decimal value by 100 and adding a literal percent sign with %%.

    double completionRate = 0.875;
    
    String result = String.format(
        "Progress: %.1f%%",
        completionRate * 100
    );
    
    System.out.println(result);

    Output:

    Progress: 87.5%

    The %% sequence displays one percent sign and does not require an argument.

    Formatting Boolean Values

    The %b specifier creates a Boolean representation.

    boolean active = true;
    
    String result = String.format(
        "Account active: %b",
        active
    );
    
    System.out.println(result);

    Output:

    Account active: true

    When %b receives a non-null object, it normally produces true. A null value produces false.

    Formatting Characters

    The %c specifier formats a character or a valid Unicode code point.

    char grade = 'A';
    
    String result = String.format(
        "Final grade: %c",
        grade
    );
    
    System.out.println(result);

    Output:

    Final grade: A

    Using uppercase %C converts applicable letters to uppercase.

    Formatting Hexadecimal and Octal Numbers

    Java can represent integers in hexadecimal and octal formats.

    Hexadecimal Example

    int number = 255;
    
    String result = String.format(
        "Hexadecimal: %x",
        number
    );
    
    System.out.println(result);

    Output:

    Hexadecimal: ff

    Use %X to display uppercase hexadecimal letters.

    String result = String.format("%X", 255);

    Output:

    FF

    Octal Example

    String result = String.format(
        "Octal: %o",
        64
    );
    
    System.out.println(result);

    Output:

    Octal: 100

    Formatting Scientific Notation

    The %e specifier formats floating-point values using scientific notation.

    double distance = 1250000.0;
    
    String result = String.format(
        "%.2e",
        distance
    );
    
    System.out.println(result);

    Output:

    1.25e+06

    Use %E when an uppercase E is preferred.

    Setting Minimum Field Width

    A width value defines the minimum number of character positions used for the output.

    String result = String.format(
        "|%10s|",
        "Java"
    );
    
    System.out.println(result);

    Output:

    |      Java|

    The value is right-aligned by default and padded with spaces on the left.

    Left-Aligning a Value

    Use the - flag to align a value to the left.

    String result = String.format(
        "|%-10s|",
        "Java"
    );
    
    System.out.println(result);

    Output:

    |Java      |

    This formatting is useful when creating console tables or aligned reports.

    Combining Width and Precision

    Width and precision can be used together.

    double amount = 123.4567;
    
    String result = String.format(
        "|%10.2f|",
        amount
    );
    
    System.out.println(result);

    Output:

    |    123.46|

    In %10.2f:

    • 10 is the minimum field width.
    • .2 limits the output to two digits after the decimal point.
    • f formats the value as a decimal number.

    Reusing and Reordering Arguments

    Java allows format specifiers to refer to arguments by position. The argument index starts at 1.

    String result = String.format(
        "%2$s scored %1$d points.",
        95,
        "Maria"
    );
    
    System.out.println(result);

    Output:

    Maria scored 95 points.

    In this example:

    • %1$d refers to the first argument.
    • %2$s refers to the second argument.

    Reusing the Previous Argument

    The < flag reuses the argument used by the previous format specifier.

    String result = String.format(
        "%s scored %<s again.",
        "Alex"
    );
    
    System.out.println(result);

    Output:

    Alex scored Alex again.

    Indexed arguments are often clearer when a format string uses the same value multiple times.

    Formatting Dates and Times

    String.format() supports date and time conversion characters. Date and time specifiers use %t or %T followed by another conversion character.

    LocalDate date = LocalDate.of(2026, 9, 12);
    
    String result = String.format(
        "Date: %tF",
        date
    );
    
    System.out.println(result);

    Output:

    Date: 2026-09-12

    Common date and time conversions include:

    SpecifierMeaning
    %tFDate in year-month-day format
    %tYFour-digit year
    %tmTwo-digit month
    %tdTwo-digit day
    %tHHour in 24-hour format
    %tMMinute
    %tSSecond
    %tBFull month name
    %tAFull weekday name

    Example:

    LocalDate date = LocalDate.of(2026, 9, 12);
    
    String result = String.format(
        Locale.US,
        "%tA, %tB %td, %tY",
        date,
        date,
        date,
        date
    );
    
    System.out.println(result);

    Output:

    Saturday, September 12, 2026

    For modern applications with complex date patterns, the java.time package and DateTimeFormatter may provide clearer and more specialized formatting.

    Using Locale With String.format()

    A locale controls regional formatting conventions, including decimal separators and digit grouping.

    double amount = 12345.67;
    
    String usValue = String.format(
        Locale.US,
        "%,.2f",
        amount
    );
    
    String germanValue = String.format(
        Locale.GERMANY,
        "%,.2f",
        amount
    );
    
    System.out.println(usValue);
    System.out.println(germanValue);

    Typical output:

    12,345.67
    12.345,67

    Using an explicit locale creates predictable output and is especially important for international applications.

    Creating Aligned Console Tables

    String.format() is useful for creating structured command-line output.

    String header = String.format(
        "%-15s %10s %10s",
        "Product",
        "Quantity",
        "Price"
    );
    
    String row = String.format(
        "%-15s %10d %10.2f",
        "Keyboard",
        5,
        49.99
    );
    
    System.out.println(header);
    System.out.println(row);

    Output:

    Product           Quantity      Price
    Keyboard                 5      49.99

    The width and alignment settings keep each value in the correct column.

    String.format() vs String Concatenation

    String concatenation uses the + operator:

    String message =
        "User " + name + " has " + points + " points.";

    The same statement with String.format() is:

    String message = String.format(
        "User %s has %d points.",
        name,
        points
    );

    String.format() is often clearer when a message contains several dynamic values or needs alignment, rounding, padding, or locale-specific formatting.

    Simple concatenation may still be appropriate for short expressions that do not require special formatting.

    String.format() vs formatted()

    Modern Java versions also allow the formatted() instance method on a format string.

    String message = "User %s has %d points."
        .formatted("Aisha", 150);

    This produces the same result as:

    String message = String.format(
        "User %s has %d points.",
        "Aisha",
        150
    );

    formatted() can be more readable when the format pattern is the main part of the expression. String.format() remains useful when an explicit locale is required or when a project follows the traditional static method style.

    String.format() vs printf()

    Both methods use similar formatting rules, but their results are handled differently.

    String.format() returns a formatted string:

    String result = String.format(
        "Score: %d",
        90
    );

    System.out.printf() writes formatted output directly to the console:

    System.out.printf(
        "Score: %d%n",
        90
    );

    Use String.format() when the result needs to be stored, returned, logged, or passed to another method. Use printf() when the output only needs to be displayed.

    Common String.format() Exceptions

    Incorrect format patterns or incompatible argument types can cause runtime exceptions.

    IllegalFormatConversionException

    This exception occurs when a format specifier does not support the supplied argument type.

    String result = String.format(
        "%d",
        "Java"
    );

    The %d specifier expects an integer-compatible value, but it receives a string.

    MissingFormatArgumentException

    This occurs when a format specifier does not have a corresponding argument.

    String result = String.format(
        "%s is %d years old.",
        "David"
    );

    The format expects two arguments, but only one is supplied.

    UnknownFormatConversionException

    This exception may occur when the format string contains an unsupported conversion.

    String result = String.format(
        "%q",
        "Java"
    );

    Java does not recognize %q as a valid conversion.

    Best Practices for Using String.format()

    Follow these practices to produce clear and reliable formatted strings:

    1. Match every format specifier with a compatible argument type.
    2. Use meaningful and readable format patterns.
    3. Specify precision when displaying currency or measurements.
    4. Use an explicit locale when output must remain regionally consistent.
    5. Prefer %n over \n for platform-independent line breaks.
    6. Avoid overly complex format strings that are difficult to maintain.
    7. Test width and alignment when creating tables.
    8. Do not use formatting alone for currency calculations.
    9. Keep translatable user messages separate when building multilingual software.
    10. Consider DateTimeFormatter for complex date and time patterns.

    Frequently Asked Questions

    What is String.format() in Java?

    String.format() is a static method that inserts supplied values into a format pattern and returns a new formatted string. It can format text, integers, decimal numbers, dates, times, Boolean values, and other objects.

    Does String.format() print the result?

    No. String.format() returns a string but does not print it automatically.

    String result = String.format(
        "Total: %.2f",
        99.95
    );
    
    System.out.println(result);

    The formatted value must be printed explicitly when console output is required.

    What does %s mean in String.format()?

    The %s specifier displays an argument as a string. If the argument is an object, Java generally uses its toString() representation.

    What does %d mean in Java formatting?

    The %d specifier formats an integer in decimal notation. It is suitable for values such as byte, short, int, long, and their corresponding wrapper types.

    How can I limit a number to two decimal places?

    Use %.2f:

    double number = 15.678;
    
    String result = String.format(
        "%.2f",
        number
    );

    The result is:

    15.68

    How do I add leading zeros in Java?

    Use the 0 flag followed by the required width.

    String result = String.format(
        "%05d",
        42
    );

    Output:

    00042

    How do I include a percent sign in String.format()?

    Use two percent signs:

    String result = String.format(
        "Success rate: %.1f%%",
        98.5
    );

    Output:

    Success rate: 98.5%

    Can String.format() format dates?

    Yes. Date and time specifiers begin with %t or %T. For example, %tF produces a date in year-month-day format. For advanced date handling, DateTimeFormatter is usually more flexible.

    What is the difference between String.format() and printf()?

    String.format() returns the formatted text as a string, while printf() sends formatted text directly to an output stream such as the console. Both use similar format specifiers.

    Does String.format() change the original string?

    No. Java strings are immutable. The method creates and returns a new string without modifying the original format pattern or supplied values.

    Is String.format() suitable for currency?

    It can format a numeric value to look like currency, but NumberFormat.getCurrencyInstance() is generally better when an application needs locale-aware currency symbols and conventions. Monetary calculations should also use an appropriate numeric type such as BigDecimal.

    Can null be used with String.format()?

    Yes, but the result depends on the conversion. For example, %s commonly formats a null reference as null, while %b produces false.

    Conclusion

    The String.format() Method in Java offers a structured way to create readable and consistent text. It can insert dynamic values, control decimal precision, align columns, add padding, format dates, and apply regional number conventions.

    Share. Facebook Twitter Pinterest LinkedIn WhatsApp Reddit Tumblr Email
    Previous ArticleTypes of Sensors and Actuators in IoT Explained
    Tiago
    • Website

    Add A Comment
    Leave A Reply Cancel Reply

    Search…
    Recent Posts

    Formatting Strings in Java: String.format() Method

    September 12, 2026

    Types of Sensors and Actuators in IoT Explained

    September 12, 2026

    Java Records in Java 16: Syntax, Features, and Examples

    September 12, 2026

    Microservices Design Patterns: Key Architecture Patterns Every Developer Should Know

    September 11, 2026

    C# String Formatting Examples: Practical Ways to Format Strings

    September 11, 2026

    Databricks Disk Cache: The Secret to Faster Repeated Analytics Workloads

    September 11, 2026
    About

    MKOVAH Magazine is your destination for fresh ideas, useful insights, and the latest trends across technology, business, lifestyle, travel, entertainment, health, and more. We bring engaging and informative content to help you stay inspired, informed, and connected with the world around you.

    Latest Posts

    Types of Sensors and Actuators in IoT Explained

    September 12, 2026

    Java Records in Java 16: Syntax, Features, and Examples

    September 12, 2026

    Microservices Design Patterns: Key Architecture Patterns Every Developer Should Know

    September 11, 2026
    Contact Us

    Our team is always available to support you and ensure you receive the help you need.

    Mail: tech4links@gmail .com
    Whatsapp: Whatsapp

    Address: Flat No. 504, Shanti Residency, MG Road, Andheri East, Mumbai, Maharashtra, India

    • About Us
    • Disclaimer
    • Privacy Policy
    • Terms & Conditions
    • Write For Us
    • Contact Us
    • Sitemap
    © 2026 | MKOVAH Magzine | All Rights Reserved

    Type above and press Enter to search. Press Esc to cancel.