CoderSathi
  • Tutorial
    • Java Tutorial
    • Swing Tutorial
    • JDBC Tutorial
    • Java String Tutorial
    • Servlet and JSP Tutorial
  • Mongo DB
  • AWS
  • DevOps
  • Linux
  • Git
Home > String > Java String Formatting Guide: printf(), String.format(), and More

Java String Tutorial

  • Introduction to String
  • String Immutability
  • Common Methods
  • String Comparison
  • Formatting in String
  • Performance Optimization
  • String Manipulation
  • Java Regex Example
  • Special Characters in String
  • String Security
  • Java 8+ String Enhancements
  • Internationalization
  • Advanced Java String Techniques
  • Java String Best Practices

Java String Formatting Guide: printf(), String.format(), and More

Learn the concepts, implementation details, and practical steps with a clean developer-focused walkthrough.

Yuba Raj Kalathoki
By Yuba Raj Kalathoki
Last updated: July 1, 2026 · 2 min read · 0 Comments
Share: in X

Table of Contents

  • Why Format Strings?
  • 1. String.format() vs System.out.printf()
  • 2. Common Format Specifiers
    • Formatting Numbers
    • Formatting Dates
  • 3. Locale-Sensitive Formatting
  • Common Mistakes
  • FAQ
    • How to format a String with multiple variables?
    • What’s the difference between %n and \n?

Why Format Strings?

String formatting lets you create dynamic, readable text by injecting variables into placeholders. Use cases include:

  • Generating log messages.
  • Building user-friendly output (e.g., currency, dates).
  • Structuring complex text (e.g., CSV/JSON).

1. String.format() vs System.out.printf()

Both methods use the same syntax but serve different purposes:

  • String.format(): Returns a formatted String.
String message = String.format("Hello, %s! You have %d messages.", "Radha", 5);  
// "Hello, Radha! You have 5 messages."  
  • System.out.printf(): Directly prints formatted text to the console.
System.out.printf("Total: $%.2f%n", 19.99);  // "Total: $19.99"  

2. Common Format Specifiers

SpecifierTypeExampleOutput
%sStringString.format("%s", "Hi")"Hi"
%dInteger"%d", 42"42"
%fFloating-point"%.2f", 3.1415"3.14"
%tFDate (ISO)"%tF", new Date()"2024-05-05"
%nNewline"Line1%nLine2""Line1\nLine2"
%%Literal %"Discount: 10%%""Discount: 10%"

Formatting Numbers

Control precision, padding, and commas:

// Precision:  
String.format("PI: %.3f", Math.PI);        // "PI: 3.142"  

// Padding:  
String.format("ID: %05d", 42);             // "ID: 00042"  

// Locale-Specific (e.g., commas):  
String.format(Locale.US, "%,d", 1000000);  // "1,000,000"  

Formatting Dates

Use %t specifiers with java.util.Date:

Date now = new Date();  
String.format("Date: %tF | Time: %tT", now, now);  
// "Date: 2024-05-05 | Time: 14:30:45"  

Key Date Specifiers:

  • %tF: ISO date (yyyy-MM-dd)
  • %tT: 24-hour time (HH:mm:ss)
  • %tD: Short date (MM/dd/yy)

3. Locale-Sensitive Formatting

Specify a Locale to format numbers/dates regionally:

// German locale uses commas as decimal separators:  
String.format(Locale.GERMAN, "%.2f", 3.14);  // "3,14"  

// US locale for currency:  
String.format(Locale.US, "$%,.2f", 1000.5);  // "$1,000.50"  

Common Mistakes

❌ Mismatched Specifiers:

String.format("%d", "text");  // Throws IllegalFormatConversionException  

❌ Missing Arguments:

String.format("Hello, %s and %s", "Radha");  // MissingSecondArgumentException  

✅ Best Practices:

  1. Use try-catch for dynamic formats.
  2. Prefer DateTimeFormatter for Java 8+ dates (Java DateTimeFormatter Example).

FAQ

How to format a String with multiple variables?

Use positional indexes (%1$s):
String.format("%1$s → %2$d → %1$s", "A", 10); // "A → 10 → A"

What’s the difference between %n and \n?

%n is platform-independent (e.g., \r\n on Windows), while \n is Unix-only.

Up Next: String Performance & Optimization: Learn to optimize concatenation with StringBuilder and avoid memory pitfalls.

Related Posts:

  • How to Convert JSON Array to Java List (With Examples)
  • JSON and BSON in MongoDB
  • Java String Manipulation: Replace, Split, and Join
  • Java String Best Practices and Common Pitfalls
  • Java JSON Serialization and Deserialization
  • How to Import and Export Data in MongoDB: A…
Tags:javalanguage-fundamentalsString
Was this article helpful?
← Previous ArticleJava String Comparison: equals(), ==, and compareTo() Explained
Next Article →Java String Performance: Optimize Concatenation with StringBuilder

Leave a Comment Cancel reply

You must be logged in to post a comment.

Recent Posts

  • How to implement Passwordless Authentication in Spring Boot: A Step-by-Step Guide
  • How to Use AWS CloudFront Signed URLs in Spring Boot?
  • How to Fix SSH Agent Forwarding on macOS: The Ultimate Guide for Developers
  • How to Read AWS Secrets Manager in Spring Boot (Step-by-Step)
  • How to Fix “Public Key Retrieval is not allowed” MySQL JDBC Error
CoderSathi

Your go-to resource for Java, Spring Boot, Microservices, AWS, and modern development tutorials.

Linkedin

Quick Links

  • About
  • Contact

Popular Topics

  • Java
  • Spring Boot
  • AWS
  • DevOps
  • MongoDB
  • Linux
  • Git
  • How to
© 2026 CoderSathi. All rights reserved. Privacy Policy · Sitemap