0
0
JavaHow-ToBeginner · 3 min read

How to Format String in Java: Syntax and Examples

In Java, you can format strings using String.format() which allows you to insert variables into a string with placeholders like %s for strings or %d for integers. This method returns a new formatted string without changing the original.
📐

Syntax

The basic syntax of string formatting in Java uses String.format() method:

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

Here, formatString contains text with placeholders like %s for strings, %d for integers, and %f for floating-point numbers. The arguments replace these placeholders in order.

java
String formatted = String.format("Hello, %s! You have %d new messages.", "Alice", 5);
System.out.println(formatted);
Output
Hello, Alice! You have 5 new messages.
💻

Example

This example shows how to format a string with a name, an integer, and a floating-point number with two decimal places.

java
public class FormatExample {
    public static void main(String[] args) {
        String name = "Bob";
        int age = 30;
        double score = 95.6789;

        String result = String.format("Name: %s, Age: %d, Score: %.2f", name, age, score);
        System.out.println(result);
    }
}
Output
Name: Bob, Age: 30, Score: 95.68
⚠️

Common Pitfalls

Common mistakes when formatting strings in Java include:

  • Using the wrong placeholder type (e.g., %d for a string).
  • Not matching the number of placeholders with the number of arguments.
  • Forgetting that String.format() returns a new string and does not change the original.

Here is an example showing a wrong and right way:

java
public class PitfallExample {
    public static void main(String[] args) {
        // Wrong: Using %d for a string causes an error
        // String wrong = String.format("Name: %d", "Alice"); // Throws java.util.IllegalFormatConversionException

        // Right: Use %s for strings
        String right = String.format("Name: %s", "Alice");
        System.out.println(right);
    }
}
Output
Name: Alice
📊

Quick Reference

PlaceholderDescriptionExample
%sString"Hello %s"
%dInteger (decimal)"Number: %d"
%fFloating-point number"Value: %.2f"
%cCharacter"Char: %c"
%bBoolean"Boolean: %b"
%%Literal percent sign"Progress: 100%%"

Key Takeaways

Use String.format() with placeholders like %s, %d, and %f to format strings in Java.
Always match the placeholder types with the argument types to avoid errors.
String.format() returns a new formatted string; it does not modify the original string.
Use %.2f to format floating-point numbers with two decimal places.
Remember to escape percent signs with %% when you want a literal percent symbol.