For working professionals
For fresh graduates
More
6. JDK in Java
7. C++ Vs Java
16. Java If-else
18. Loops in Java
20. For Loop in Java
45. Packages in Java
52. Java Collection
55. Generics In Java
56. Java Interfaces
59. Streams in Java
62. Thread in Java
66. Deadlock in Java
73. Applet in Java
74. Java Swing
75. Java Frameworks
77. JUnit Testing
80. Jar file in Java
81. Java Clean Code
85. Java 8 features
86. String in Java
92. HashMap in Java
97. Enum in Java
100. Hashcode in Java
104. Linked List in Java
108. Array Length in Java
110. Split in java
111. Map In Java
114. HashSet in Java
117. DateFormat in Java
120. Java List Size
121. Java APIs
127. Identifiers in Java
129. Set in Java
131. Try Catch in Java
132. Bubble Sort in Java
134. Queue in Java
141. Jagged Array in Java
143. Java String Format
144. Replace in Java
145. charAt() in Java
146. CompareTo in Java
150. parseInt in Java
152. Abstraction in Java
153. String Input in Java
155. instanceof in Java
156. Math Floor in Java
157. Selection Sort Java
158. int to char in Java
163. Deque in Java
171. Trim in Java
172. RxJava
173. Recursion in Java
174. HashSet Java
176. Square Root in Java
189. Javafx
String formatting is used in Java applications for clean, readable, and well-structured output. Whether it's logging system events, generating reports, or displaying user-friendly data, proper formatting enhances clarity and efficiency.
Unlike manual concatenation, String.format() provides a more flexible, efficient, and maintainable way to handle formatted strings.
In this tutorial, you'll learn how to use Java's String.format() method, explore different formatting options for numbers, dates, and text, and understand its real-world applications in software development.
Improve your Java programming skills with our Software Development courses — take the next step in your learning journey!
The String.format() method in Java is a powerful utility for formatting strings dynamically. It allows you to insert values into a formatted template, making output more readable and structured.
Basic Syntax:
String formattedString = String.format("format-string", arguments);
Here,
Let’s get into the Java String formatting examples.
Example 1: Formatting Numbers and Strings
public class StringFormatExample {
public static void main(String[] args) {
// Formatting a string and an integer
String name = "Alice";
int age = 25;
// Using %s for strings and %d for integers
String formatted = String.format("Name: %s, Age: %d", name, age);
System.out.println(formatted);
}
}
Output:
Name: Alice, Age: 25
Explanation:
Example 2: Formatting Decimals with Precision
public class DecimalFormatExample {
public static void main(String[] args) {
double price = 5.6789;
// Formatting to 2 decimal places
String formattedPrice = String.format("Price: %.2f", price);
System.out.println(formattedPrice);
}
}
Output:
Price: 5.68
Explanation:
Example 3: Padding and Alignment
public class PaddingExample {
public static void main(String[] args) {
// Left-align (-) and right-align integers within a 10-character space
String leftAligned = String.format("|%-10s|", "Java");
String rightAligned = String.format("|%10s|", "Java");
System.out.println(leftAligned);
System.out.println(rightAligned);
}
}
Output:
|Java |
| Java|
Explanation:
Here are the key takeaways:
Also Read: Exploring the 14 Key Advantages of Java: Why It Remains a Developer's Top Choice in 2025
Now that you understand how String.format() works, it's essential to dive into the format specifiers that make it so powerful. Different placeholders allow you to format numbers, strings, dates, and more with precision and flexibility.
The String.format() method in Java supports format specifiers, which allow you to format different types of data consistently and efficiently. Each specifier defines how a value should be displayed in the final string.
Here are basic format specifiers:
Specifier | Data Type | Example Usage |
%s | String | "Hello, %s!" → "Hello, Java!" |
%d | Integer (decimal) | "Age: %d" → "Age: 25" |
%f | Floating-point number | "Price: %.2f" → "Price: 9.99" |
%c | Character | "Initial: %c" → "Initial: J" |
Now, let’s get into the Java String formatting examples.
Example 1: Formatting Strings and Numbers
public class FormatSpecifiersExample {
public static void main(String[] args) {
// Declaring variables
String name = "Alice";
int age = 25;
// Using %s for strings and %d for integers
String formatted = String.format("My name is %s and I am %d years old.", name, age);
// Printing formatted output
System.out.println(formatted);
}
}
Output:
My name is Alice and I am 25 years old.
Explanation:
Example 2: Formatting Floating-Point Numbers
public class FloatingPointFormat {
public static void main(String[] args) {
double price = 9.9876;
// Formatting floating-point number to 2 decimal places
String formattedPrice = String.format("Total Price: %.2f", price);
System.out.println(formattedPrice);
}
}
Output:
Total Price: 9.99
Explanation: %.2f ensures the floating-point number is rounded to two decimal places.
Example 3: Formatting Characters
public class CharacterFormat {
public static void main(String[] args) {
char initial = 'J';
// Formatting a character using %c
String formattedChar = String.format("First letter: %c", initial);
System.out.println(formattedChar);
}
}
Output:
First letter: J
Explanation: %c is used to format and print a single character.
Here are the key takeaways:
Also Read: String Functions In Java | Java String [With Examples]
Java's String.format() method provides powerful number formatting options, making it easier to present numbers in a readable and structured way. This includes padding, thousands separators, decimal precision, and scientific notation.
Now, let’s get into the Java String formatting examples.
1. Integer Formatting in Java
Specifier | Description | Example Output |
%d | Formats an integer | 1234 → 1234 |
%05d | Pads the number with leading zeros (5 digits) | 42 → 00042 |
%,d | Formats number with a thousands separator | 1000000 → 1,000,000 |
Example: Padding and Thousand Separators
public class IntegerFormattingExample {
public static void main(String[] args) {
int number = 1000;
int smallNumber = 42;
// Formatting with thousands separator
String formattedNumber = String.format("Formatted Number: %,d", number);
// Padding with leading zeros (5-digit width)
String paddedNumber = String.format("Padded Number: %05d", smallNumber);
System.out.println(formattedNumber);
System.out.println(paddedNumber);
}
}
Output:
Formatted Number: 1,000
Padded Number: 00042
Explanation:
2. Floating-Point Formatting in Java
Specifier | Description | Example Output |
%.2f | Rounds to 2 decimal places | 1234.567 → 1234.57 |
%.3e | Formats as scientific notation (3 decimals) | 1234.567 → 1.235e+03 |
Example: Controlling Decimal Places & Scientific Notation
public class FloatingPointFormatting {
public static void main(String[] args) {
double price = 1234.567;
// Formatting to 2 decimal places
String formattedPrice = String.format("Price: %.2f", price);
// Formatting in scientific notation with 3 decimal places
String scientificFormat = String.format("Scientific Notation: %.3e", price);
System.out.println(formattedPrice);
System.out.println(scientificFormat);
}
}
Output:
Price: 1234.57
Scientific Notation: 1.235e+03
Explanation:
Here are the takeaways:
Also Read: Ultimate Guide to Synchronization in Java
Java's String.format() method provides built-in date and time formatting using %t specifiers. These specifiers allow you to extract and format different parts of a Date object without relying on external libraries.
Here are the common data and time specifiers:
Specifier | Description | Example Output |
%tY | Full year (4 digits) | 2025 |
%ty | Last two digits of year | 25 |
%tm | Month (2 digits) | 02 |
%td | Day of the month (2 digits) | 26 |
%tH | Hour (24-hour format) | 14 |
%tM | Minutes | 30 |
%tS | Seconds | 45 |
%tp | AM/PM marker | PM |
Now, let’s get into the Java String formatting examples.
Example 1: Formatting Date (YYYY-MM-DD)
import java.util.Date;
public class DateFormatExample {
public static void main(String[] args) {
Date now = new Date();
// Formatting date in YYYY-MM-DD format
String formattedDate = String.format("Date: %tY-%tm-%td", now, now, now);
System.out.println(formattedDate);
}
}
Output:
Date: 2025-02-26
Explanation:
Example 2: Formatting Time (HH:MM:SS AM/PM)
import java.util.Date;
public class TimeFormatExample {
public static void main(String[] args) {
Date now = new Date();
// Formatting time in HH:MM:SS AM/PM format
String formattedTime = String.format("Time: %tI:%tM:%tS %tp", now, now, now, now);
System.out.println(formattedTime);
}
}
Output:
Time: 02:30:45 PM
Explanation:
Example 3: Full Date and Time Formatting
import java.util.Date;
public class FullDateTimeExample {
public static void main(String[] args) {
Date now = new Date();
// Formatting full date and time
String formattedDateTime = String.format("Date & Time: %tA, %tB %td, %tY - %tI:%tM %tp",
now, now, now, now, now, now, now);
System.out.println(formattedDateTime);
}
}
Output:
Date & Time: Wednesday, February 26, 2025 - 02:30 PM
Explanation:
Here are the takeaways:
Also Read: Multithreading in Java - Learn with Examples
Java's String.format() provides powerful formatting options for aligning text and padding numbers, making output more structured and readable. You can left-align, right-align, or pad values with spaces or zeros for better presentation in reports, tables, and logs.
Left & Right Alignment in String Formatting:
Specifier | Description | Example Output |
%-10s | Left-aligns a string within 10 spaces | "Hello" → "Hello " |
%10s | Right-aligns a string within 10 spaces | "World" → " World" |
%10d | Right-aligns a number within 10 spaces | 123 → " 123" |
Now, let’s get into the Java String formatting examples.
Example: Left & Right Alignment in Strings
public class AlignmentExample {
public static void main(String[] args) {
// Left-align text using %-10s and right-align using %10s
String formatted = String.format("|%-10s|%10s|", "Left", "Right");
System.out.println(formatted);
}
}
Output:
|Left | Right|
Explanation:
Padding Strings and Numbers in Java:
Specifier | Description | Example Output |
%10s | Pads a string with default spaces (right-aligned) | "Hi" → " Hi" |
%010d | Pads a number with leading zeros to 10 digits | 123 → "0000000123" |
Example: Padding Numbers with Leading Zeros
public class NumberPaddingExample {
public static void main(String[] args) {
int number = 123;
// Right-align and pad with leading zeros (10 characters wide)
String paddedNumber = String.format("|%010d|", number);
System.out.println(paddedNumber);
}
}
Output:
|0000000123|
Explanation: %010d ensures the number is at least 10 digits long, adding leading zeros if needed.
Example: Combining Alignment & Padding in a Table Format
public class TableFormattingExample {
public static void main(String[] args) {
System.out.println(String.format("|%-15s|%10s|%10s|", "Item", "Qty", "Price"));
System.out.println(String.format("|%-15s|%10d|%10.2f|", "Apples", 5, 2.99));
System.out.println(String.format("|%-15s|%10d|%10.2f|", "Bananas", 12, 1.49));
}
}
Output:
|Item | Qty| Price|
|Apples | 5| 2.99|
|Bananas | 12| 1.49|
Explanation:
%-15s ensures item names are left-aligned within 15 spaces.
Here are the takeaways:
Also Read: Top 13 String Functions in Java | Java String [With Examples]
Java's String.format() allows handling special characters like % for percentages and \n for newlines. However, Java also provides platform-independent escape sequences like %n, ensuring consistent behavior across different operating systems.
Now, let’s get into the Java String formatting examples.
1. Handling % in Strings
Since % is a special character in String.format(), you must use %% to print a literal percent sign (%).
Example: Printing a Percentage
public class PercentageExample {
public static void main(String[] args) {
// Printing a percentage symbol using %%
String formatted = String.format("Discount: 10%%");
System.out.println(formatted);
}
}
Output:
Discount: 10%
Explanation: Using %% ensures % is displayed as a normal character instead of being treated as a format specifier.
2. Newline: %n vs \n
Java provides two ways to insert newlines in formatted strings:
Newline Character | Behavior |
%n | Platform-independent newline (Windows, macOS, Linux) |
\n | Standard newline (may not work consistently on all platforms) |
Example: Using %n for Cross-Platform Newlines
public class NewlineExample {
public static void main(String[] args) {
// Using platform-independent newline %n
String formatted = String.format("Line 1%nLine 2");
System.out.println(formatted);
}
}
Output (same across all platforms):
Line 1
Line 2
Explanation: %n ensures consistent line breaks regardless of the operating system.
Example: \n vs %n Behavior
public class NewlineComparison {
public static void main(String[] args) {
// Using %n (Cross-platform)
System.out.println(String.format("Using %%n:%nLine A%nLine B"));
// Using \n (May behave differently across platforms)
System.out.println("Using \\n:\nLine X\nLine Y");
}
}
Output (Windows vs Linux/macOS): On Linux/macOS, both will print correctly.
Using %n:
Line A
Line B
Using \n:
Line X
Line Y
On Windows, \n might not work correctly in certain console environments, while %n remains consistent.
Here are the takeaways:
Also Read: Length Of String In Java
While String.format() is a convenient way to format strings, Java offers other approaches for handling text formatting efficiently. Depending on your use case, StringBuilder, MessageFormat, and external libraries can provide better performance and flexibility.
While String.format() is a powerful built-in method for formatting strings, Java provides alternative approaches for more efficient, localized, or complex string manipulation. These methods include StringBuilder, MessageFormat, and external libraries like Apache Commons.
1. Using StringBuilder and StringBuffer for Efficient Concatenation
Using + for string concatenation inside loops creates multiple immutable string objects, leading to performance overhead. Instead, StringBuilder (non-thread-safe) or StringBuffer (thread-safe) should be used for efficient string concatenation.
Example: Using StringBuilder
public class StringBuilderExample {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
// Efficiently appending strings
sb.append("Hello, ");
sb.append("World!");
System.out.println(sb.toString()); // Output: Hello, World!
}
}
Explanation: StringBuilder avoids creating multiple immutable string objects, improving performance.
2. Using MessageFormat for Advanced Formatting and Localization
The MessageFormat class provides powerful placeholders {0}, {1}, {2}..., making it easier to format strings dynamically, especially for localized messages.
Example: Using MessageFormat for Dynamic Formatting
import java.text.MessageFormat;
public class MessageFormatExample {
public static void main(String[] args) {
String template = "Hello {0}, you have {1} new messages.";
// Formatting with dynamic values
String formatted = MessageFormat.format(template, "Alice", 5);
System.out.println(formatted);
}
}
Output:
Hello Alice, you have 5 new messages.
Explanation: MessageFormat is ideal for localized messages, as it automatically handles number formats and different locales.
3. Using External Libraries (Apache Commons StringUtils)
For complex string manipulation, libraries like Apache Commons Lang provide additional utilities that are more concise and readable than Java’s built-in methods.
Example: Using StringUtils for Joining Strings
import org.apache.commons.lang3.StringUtils;
public class ApacheStringUtilsExample {
public static void main(String[] args) {
// Joining multiple strings with a separator
String result = StringUtils.join(new String[]{"Java", "Servlets", "Spring"}, " - ");
Output:
Java - Servlets - Spring
Explanation: StringUtils.join() simplifies joining arrays or collections into a formatted string.
Here are the takeaways:
Also Read: Difference Between String and StringBuffer in Java
Even with multiple formatting options, developers often encounter runtime errors, precision issues, or unexpected outputs. Understanding these common pitfalls will help you debug formatting issues efficiently and ensure consistent results.
While String.format() simplifies string manipulation, incorrect usage can lead to runtime errors, unexpected outputs, or data loss. Common issues include mismatched format specifiers, handling null values, and precision loss in floating-point formatting.
The table below highlights frequent mistakes and their solutions:
Issue | Cause | Solution |
Mismatched Format Specifiers | Using %s for numbers or %d for strings | Ensure the correct specifier (%d for integers, %s for strings, %f for floating-point numbers) |
NullPointerException | Passing null to String.format() | Use String.valueOf(null) or replace null with a default value |
Precision Loss in Floating-Point Formatting | Rounding errors when formatting decimals | Use %.2f for controlled precision and BigDecimal for high-precision calculations |
Being aware of these pitfalls ensures more robust and predictable string formatting in Java applications.
Also Read: String Array In Java: Java String Array With Coding Examples
Avoiding common mistakes is just one part of writing clean, efficient code. To get the most out of String.format(), follow best practices that improve readability, performance, and maintainability in your Java applications.
Using String.format() effectively enhances code readability, performance, and structured output. Here are key best practices to follow:
1. Avoid unnecessary string concatenation – Instead of "Hello, " + name + "!", use String.format("Hello, %s!", name); for better readability and performance.
2. Use String.format() in logging – Structured logs improve debugging. Example:
logger.info(String.format("User %s logged in at %tT", username, new Date()));
3. Prefer System.out.printf() for console output – Instead of System.out.println(), use System.out.printf("Total Price: %.2f%n", price); to format inline.
4. Consider Formatter for complex formatting needs – When writing formatted output to files or streams, Formatter offers more control:
Formatter formatter = new Formatter();
formatter.format("Name: %s, Age: %d", name, age);
System.out.println(formatter);
formatter.close();
Applying these practices ensures cleaner, more efficient, and well-structured Java applications!
Also Read: Top 8 Reasons Why Java Is So Popular and Widely Used in 2025
To solidify your understanding of Java string format, test your knowledge with this quiz. It’ll help reinforce the concepts discussed throughout the blog and ensure you're ready to apply them in your projects.
Assess your grasp of format specifiers, alignment, padding, date formatting, and best practices by answering the following multiple-choice questions. Dive in!
1. Which format specifier is used to format floating-point numbers in Java?
a) %s
b) %d
c) %f
d) %c
2. What will be the output of String.format("Price: %.2f", 5.6789);?
a) Price: 5.6789
b) Price: 5.67
c) Price: 5.68
d) Price: 6.00
3. Which of the following correctly prints a literal percentage sign (%) in String.format()?
a) "%%"
b) "%p"
c) "%"
d) "p%"
4. How do you properly format an integer with leading zeros to always have at least 5 digits?
a) %05d
b) %5d
c) %d5
d) %d
5. Which method provides platform-independent newline formatting in Java?
a) \n
b) \r
c) %n
d) \t
6. What is the difference between %n and \n in Java string formatting?
a) %n is cross-platform, while \n may not work consistently on all systems
b) %n adds a space, while \n adds a newline
c) There is no difference between them
d) \n works only on Windows, while %n is for Linux
7. Which class is best suited for formatting numbers with locale-specific thousands separators (e.g., 1,000 instead of 1000)?
a) String.format()
b) Formatter
c) NumberFormat
d) MessageFormat
8. What is the output of System.out.printf("|%-10s|%10s|", "Left", "Right");?
a) |Left |Right |
b) | Left|Right |
c) |Left | Right|
d) | Left|Right |
9. Which alternative method should you prefer over String.format() for high-performance string concatenation in loops?
a) StringBuffer
b) StringBuilder
c) Formatter
d) String.join()
10. Which of the following methods is best suited for formatting log messages dynamically in Java?
a) String.format()
b) MessageFormat.format()
c) Logger.info(String.format())
d) All of the above
Also Read: How to do Reverse String in Java?
You can continue expanding your skills in Java with upGrad, which will help you deepen your understanding of advanced Java concepts and real-world applications.
You can continue expanding your skills in Java with upGrad, which will help you deepen your understanding of advanced Java concepts and real-world applications.
upGrad’s courses offer expert training on Java string formatting, text manipulation, and best practices for structured output. You’ll gain hands-on experience working with format specifiers, number and date formatting, logging, and performance optimization.
Mastering these concepts is essential for building professional applications, improving data presentation, and ensuring platform-independent formatting.
Below are some relevant upGrad courses:
You can also get personalized career counseling with upGrad to guide your career path, or visit your nearest upGrad center and start hands-on training today!
Similar Reads:
Q: Why does String.format("%d", null); throw a NullPointerException, but String.format("%s", null); works fine?
A: %d expects a numeric value, and passing null causes an error. %s works because it automatically converts null to "null" as a string.
Q: How can I format a BigDecimal without scientific notation using String.format()?
A: Use %.2f for decimal precision, but for precise control over BigDecimal, prefer .toPlainString() instead of String.format().
Q: Why does String.format("%.0f", 2.5); return 2 instead of rounding up to 3?
A: String.format() uses bankers’ rounding, meaning .5 values round to the nearest even number. Use Math.round() for conventional rounding.
Q: How do I handle different locales when formatting numbers and dates?
A: Use String.format(Locale.US, "%.2f", 1234.56); to enforce a locale, or leverage NumberFormat.getInstance(Locale) for internationalized formatting.
Q: Why does String.format("%05d", 1000000); ignore zero padding?
A: Zero padding applies only when the number has fewer digits than the specified width. Since 1000000 has more than five digits, padding is ignored.
Q: Can I use String.format() to dynamically determine the width of formatted text?
A: Yes, use %*d or %*s where the width is specified as an argument: String.format("%*d", 10, 42); results in " 42".
Q: Why does String.format("%.2f", 0.1 + 0.2); return 0.30 instead of 0.3?
A: Floating-point arithmetic introduces precision errors. String.format() does not fix underlying inaccuracies but simply rounds the displayed output.
Q: How do I format a hexadecimal number using String.format()?
A: Use %x or %X for lowercase/uppercase hex formatting: String.format("Hex: %x", 255); results in Hex: ff.
Q: Why does String.format("%,d", 1000); work for numbers but not for double values?
A: %d automatically applies locale-specific grouping for integers. For doubles, you need %,.2f: String.format("%,.2f", 1000.0); results in 1,000.00.
Q: How do I dynamically format a currency value based on a locale using String.format()?
A: String.format(Locale.US, "$%,.2f", 1234.56); works for simple cases, but for robust currency formatting, use NumberFormat.getCurrencyInstance(Locale).
Q: Why does String.format("%-10s", "Hello"); not align text properly in some console environments?
A: Some terminals use proportional fonts, causing spacing inconsistencies. Consider using monospaced fonts or external libraries like Apache Commons for precise alignment.
Take the Free Quiz on Java
Answer quick questions and assess your Java knowledge
Author
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918068792934
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.