0
0
JavaHow-ToBeginner · 3 min read

How to Use Format in Java String: Simple Guide

In Java, you can use String.format() to create formatted strings by specifying a format pattern and values. The format uses placeholders like %s for strings and %d for integers, which get replaced by the provided arguments.
📐

Syntax

The basic syntax of String.format() is:

  • String.format(formatString, arguments...)

Here, formatString contains text with placeholders, and arguments are the values to insert.

Common placeholders include:

  • %s - string
  • %d - integer
  • %f - floating-point number
java
String formatted = String.format("Hello, %s! You have %d new messages.", "Alice", 5);
💻

Example

This example shows how to use String.format() to insert a name and a number into a message.

java
public class FormatExample {
    public static void main(String[] args) {
        String name = "Alice";
        int messages = 5;
        String formatted = String.format("Hello, %s! You have %d new messages.", name, messages);
        System.out.println(formatted);
    }
}
Output
Hello, Alice! You have 5 new messages.
⚠️

Common Pitfalls

Common mistakes when using String.format() include:

  • Mismatch between placeholders and argument types (e.g., using %d but passing a string).
  • Wrong number of arguments compared to placeholders.
  • Forgetting to use String.format() and trying to use placeholders directly in strings.
java
public class FormatPitfall {
    public static void main(String[] args) {
        // Wrong: passing string to %d placeholder
        // String result = String.format("Number: %d", "five"); // Causes runtime error

        // Correct usage:
        String result = String.format("Number: %d", 5);
        System.out.println(result);
    }
}
Output
Number: 5
📊

Quick Reference

PlaceholderDescriptionExample
%sString"%s" -> "hello"
%dInteger (decimal)"%d" -> 42
%fFloating-point number"%.2f" -> 3.14
%cCharacter"%c" -> 'A'
%%Literal percent sign"%%" -> "%"

Key Takeaways

Use String.format() with placeholders like %s and %d to create formatted strings.
Ensure the number and types of arguments match the placeholders exactly.
Common placeholders include %s for strings, %d for integers, and %f for floats.
String.format() returns a new formatted string; it does not change the original string.
Use %% to include a literal percent sign in the output.