How to Use printf in Java: Syntax and Examples
In Java,
printf is used to print formatted text to the console. You use it by calling System.out.printf with a format string and optional arguments to insert values in a specific format.Syntax
The basic syntax of printf in Java is:
System.out.printf(format, args...);
Here, format is a string that contains text and format specifiers like %d for integers or %s for strings. The args are the values to insert into the format string.
java
System.out.printf("format string", arguments);
Example
This example shows how to print a formatted message with a string and an integer using printf. It demonstrates inserting values into the format string.
java
public class PrintfExample { public static void main(String[] args) { String name = "Alice"; int age = 30; System.out.printf("%s is %d years old.%n", name, age); } }
Output
Alice is 30 years old.
Common Pitfalls
Common mistakes when using printf include:
- Not matching the number of format specifiers with the number of arguments.
- Using the wrong format specifier for the data type (e.g.,
%dfor a string). - Forgetting to include
\nor%nfor a new line if needed.
These cause runtime errors or incorrect output.
java
public class PrintfMistake { public static void main(String[] args) { String name = "Bob"; // Wrong: missing argument for %d // System.out.printf("Name: %s, Age: %d\n", name); // Correct: int age = 25; System.out.printf("Name: %s, Age: %d\n", name, age); } }
Output
Name: Bob, Age: 25
Quick Reference
| Format Specifier | Description | Example |
|---|---|---|
| %d | Decimal integer | 42 |
| %s | String | "hello" |
| %f | Floating-point number | 3.14 |
| %c | Character | 'A' |
| %n | Platform-specific newline | (new line) |
| %% | Literal percent sign | % |
Key Takeaways
Use System.out.printf with a format string and matching arguments for formatted output.
Match format specifiers like %d, %s, %f to the correct data types.
Always ensure the number of specifiers matches the number of arguments.
Include \n or %n for new lines to keep output readable.
Common errors come from mismatched specifiers or missing arguments.