How to Use String Format in Java: Simple Guide
In Java, you use
String.format() to create formatted strings by specifying a format string with placeholders and providing values to fill them. This method returns a new string with the values inserted according to the format specifiers.Syntax
The basic syntax of String.format() is:
String.format(formatString, arguments...)
Here, formatString contains text and format specifiers like %s for strings, %d for integers, and %f for floating-point numbers. The arguments are the values that replace these specifiers in order.
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 string with proper formatting.
java
public class Main { 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 include:
- Using the wrong format specifier for the data type (e.g.,
%dfor a string). - Not matching the number of specifiers with the number of arguments.
- Forgetting that
String.format()returns a new string and does not change the original string.
java
public class Main { public static void main(String[] args) { // Wrong: Using %d for a string // String result = String.format("Name: %d", "Alice"); // Causes runtime error // Correct: String result = String.format("Name: %s", "Alice"); System.out.println(result); } }
Output
Name: Alice
Quick Reference
| Format Specifier | Description | Example |
|---|---|---|
| %s | String | "Hello" |
| %d | Integer (decimal) | 123 |
| %f | Floating-point number | 3.14 |
| %c | Character | 'A' |
| %% | Literal percent sign | % |
Key Takeaways
Use String.format() with format specifiers like %s, %d, and %f to create formatted strings.
Always match the number and type of format specifiers with the arguments provided.
String.format() returns a new string; it does not modify the original string.
Common errors come from mismatched specifiers and argument types.
Use %% to include a literal percent sign in the output.