- 1 1. Introduction
- 2 2. Basics of System.out.print and System.out.println
- 3 3. Formatted Output with System.out.printf
- 4 4. Working with String.format
- 5 5. Advanced Techniques
- 6 6. Practical Examples for Debugging and Logging
- 7 7. Common Mistakes and Pitfalls
- 8 8. Summary
- 9 9. FAQ (Frequently Asked Questions)
- 9.1 Q1. How can I output only a newline?
- 9.2 Q2. Can mixing print and println cause unexpected line breaks?
- 9.3 Q3. What is the difference between printf and String.format?
- 9.4 Q4. Can non-ASCII characters be displayed correctly with printf?
- 9.5 Q5. How can I control the number of decimal places for numeric output?
- 9.6 Q6. How can I display array or list contents clearly?
- 9.7 Q7. What should I do with print statements before production release?
- 9.8 Q8. How can I save output to a file?
1. Introduction
When writing programs in Java, one of the most frequently used operations is output. In particular, the keyword “print” is widely used by beginners and advanced developers alike, appearing in many situations such as displaying messages on the console, checking variable values, and debugging.
In this article, we will clearly explain the differences and usage of the representative Java output methods: print, println, and printf. In addition to simple string output, we will introduce practical code examples covering numbers, variables, formatted output, and handling strings that include non-ASCII characters.
We will also cover common questions, typical errors, and advanced output techniques. This makes the article useful not only for Java beginners, but also for those returning to Java after a while or anyone who feels unsure about the differences between the print-related methods.
By the end of this article, you will have a solid understanding of Java output methods—from the basics to advanced usage—and be able to display output and debug your programs exactly as intended.
2. Basics of System.out.print and System.out.println
The most commonly used output methods in Java are System.out.print and System.out.println. Both methods display strings or numeric values to standard output (usually the console), but the key difference is whether a newline is added automatically.
2-1. How to Use System.out.print
System.out.print outputs the specified content as-is, but does not automatically add a newline. When executed multiple times, all output appears on the same line.
System.out.print("Hello");
System.out.print("Java");Output:
HelloJava2-2. How to Use System.out.println
On the other hand, System.out.println automatically adds a newline after output. This ensures that the next output starts on a new line.
System.out.println("Hello");
System.out.println("Java");Output:
Hello
Java2-3. Outputting Variables and Numbers
Both methods can output not only strings, but also numbers, variables, and calculation results. You cannot pass multiple values separated by commas, but you can concatenate values using the + operator.
int num = 10;
String name = "Java";
System.out.println("The number is " + num + ", and the language is " + name + ".");Output:
The number is 10, and the language is Java.2-4. When to Use print vs println
- print: Use when you want to display values continuously on the same line without line breaks.
- println: Use when you want to organize output line by line.
Mastering these basic differences will make Java output processing much clearer and more efficient.
3. Formatted Output with System.out.printf
System.out.printf allows you to format output using special symbols called format specifiers. This makes it possible to align digits, control decimal places, and display multiple values in a clean and readable format.
3-1. Basic Usage
System.out.printf("format", value1, value2, ...);
The first argument specifies how the output should be formatted, and the subsequent arguments provide the values.
int age = 25;
String name = "Sato";
System.out.printf("%s is %d years old.", name, age);Output:
Sato is 25 years old.%s: String%d: Integer
3-2. Common Format Specifiers
| Specifier | Description | Example |
|---|---|---|
%d | Integer (decimal) | %d → 10 |
%f | Floating-point number | %f → 3.141593 |
%s | String | %s → “Java” |
Specifying decimal places:
double pi = 3.14159;
System.out.printf("Pi is %.2f.", pi);Output:
Pi is 3.14.%.2fmeans display up to two decimal places.
3-3. Alignment and Padding
You can specify the width of numbers and strings to align output neatly.
System.out.printf("%-10s : %5d\n", "Apple", 120);
System.out.printf("%-10s : %5d\n", "Orange", 80);Output:
Apple : 120
Orange : 80%10s: Right-aligned within 10 characters%-10s: Left-aligned within 10 characters%5d: Right-aligned integer with width 5
3-4. printf vs print / println
- print / println: Simple output, suitable for quick display.
- printf: Ideal for reports or tabular data where formatting matters.
4. Working with String.format
String.format uses the same formatting mechanism as printf, but instead of printing directly, it returns a formatted string. This string can be stored in variables, written to files, or reused later.
4-1. Basic Usage of String.format
String.format("format", value1, value2, ...) returns a newly formatted string.
String name = "Tanaka";
int score = 95;
String message = String.format("%s scored %d points.", name, score);
System.out.println(message);Output:
Tanaka scored 95 points.4-2. Differences Between printf and String.format
System.out.printf: Outputs directly to standard output (no return value).String.format: Returns a string that can be reused or combined.
4-3. Reusing Formatted Strings
Formatted strings created with String.format can be reused multiple times.
String logMessage = String.format("Error code: %04d", 7);
System.out.println(logMessage);
System.out.println(logMessage.toUpperCase());Output:
Error code: 0007
ERROR CODE: 00074-4. Integration with Other APIs
Strings created with String.format can be used for file output, logging, or GUI display. When you need formatted data for later use rather than immediate output, String.format is the better choice.
5. Advanced Techniques
Java output is not limited to simple strings and numbers. In real-world scenarios, you may need to display arrays, objects, or handle OS-dependent line separators. This section introduces useful advanced techniques.
5-1. Outputting Arrays and Lists
When you output arrays or collections directly using print, their contents are not displayed as expected. For arrays, use Arrays.toString(). For lists, toString() works by default.
Example (Array):
int[] numbers = {1, 2, 3, 4, 5};
System.out.println(Arrays.toString(numbers));Output:
[1, 2, 3, 4, 5]Be sure to include import java.util.Arrays;.
Example (List):
List<String> fruits = Arrays.asList("Apple", "Orange", "Grape");
System.out.println(fruits);Output:
[Apple, Orange, Grape]6. Practical Examples for Debugging and Logging
Java output methods are extremely useful for checking program behavior and identifying errors. During development, print, println, and printf are often used to inspect variable values and execution flow. This section explains key points and precautions when using output for debugging or simple logging.
6-1. Output for Debugging
When you want to check variable values or track execution progress, System.out.println is commonly used for quick inspection.
int total = 0;
for (int i = 1; i <= 5; i++) {
total += i;
System.out.println("i = " + i + ", total = " + total);
}Output:
i = 1, total = 1
i = 2, total = 3
i = 3, total = 6
i = 4, total = 10
i = 5, total = 15By printing variable values and processing steps like this, you can quickly detect bugs or unexpected behavior.
6-2. Output in Conditional Branches and Error Situations
When a program does not behave as expected or encounters errors under specific conditions, printing contextual information makes root-cause analysis easier.
String input = null;
if (input == null) {
System.out.println("Input is null. Data retrieval may have failed.");
}6-3. Using Output as Simple Logs
In production systems, logging frameworks such as java.util.logging.Logger or external libraries like Log4j are typically used instead of System.out.println. However, for personal projects, learning, or quick checks, standard output is often sufficient.
Simple log example:
System.out.println("[INFO] Program started");
System.out.println("[ERROR] Failed to load file");Output:
[INFO] Program started
[ERROR] Failed to load file6-4. Precautions When Using Output for Debugging
- Debug output is helpful during development, but in production environments you must be careful to avoid leaving unnecessary output or exposing sensitive information.
- Before release, remove debug output or replace it with a proper logging framework.
Using output methods appropriately allows you to troubleshoot efficiently and improve program quality.
7. Common Mistakes and Pitfalls
Although Java output methods are simple, beginners often stumble over subtle issues. This section summarizes common mistakes and important points to watch out for.
7-1. Confusing print and println
Since print does not add a newline and println does, mixing them carelessly can lead to unexpected output layouts.
System.out.print("A");
System.out.print("B");
System.out.println("C");
System.out.print("D");Output:
ABC
DTip:
- Only
printlnadds a newline. Always consider output order and layout.
7-2. Mistakes When Concatenating Strings and Numbers
When concatenating strings and numbers, incorrect use of the + operator can produce unintended results.
int x = 10;
int y = 20;
System.out.println("Total is " + x + y);Output:
Total is 1020Correct example:
System.out.println("Total is " + (x + y));Output:
Total is 30Tip:
- Use parentheses when you want arithmetic to be evaluated before concatenation.
7-3. Incorrect Format Specifiers in printf
With printf, runtime errors or warnings may occur if the number or type of format specifiers does not match the arguments.
System.out.printf("%d %s", 123);→ Runtime error or unexpected behavior
Tips:
- Ensure the number of format specifiers matches the number of arguments
- Use correct types (
%dfor integers,%ffor floating-point numbers,%sfor strings)
7-4. Alignment Issues with Non-ASCII Characters
When using width specifiers (for example, %10s) with printf, alignment may break for non-ASCII or full-width characters. This is because such characters typically occupy more display width than ASCII characters. If visual alignment is important, consider the output environment, font, and editor.
7-5. Forgetting to Remove Debug Output
Be careful not to leave debug print or println statements in production code. Unnecessary output can clutter logs and, in some cases, lead to information leakage.
8. Summary
This article covered commonly used Java output methods—print, println, and printf—as well as formatted string generation using String.format and practical advanced techniques. Below is a concise summary of their characteristics and recommended usage.
8-1. Summary of Key Methods
| Method | Characteristics | Main Use Cases |
|---|---|---|
System.out.print | Outputs without a newline | Continuous output on the same line |
System.out.println | Automatically adds a newline | Line-by-line output |
System.out.printf | Formatted output using specifiers | Tables, alignment, numeric formatting |
String.format | Returns a formatted string | Logs, emails, file output |
8-2. Choosing the Right Method
- Simple display or debugging →
print,println - Readable tables or aggregated data →
printf - Reusable formatted strings or further processing →
String.format
8-3. Practical Advice
- Start with
printlnas the default and switch toprint,printf, orString.formatas needed. - Advanced output, such as arrays, objects, or OS-independent newlines, can be implemented easily using standard libraries.
- Always watch out for formatting mistakes, operator precedence issues, and forgotten debug output.
Output processing is essential for visibility and verification in programming. Apply these techniques to make your Java development more efficient and comfortable.
9. FAQ (Frequently Asked Questions)
Q1. How can I output only a newline?
A1.
You can output only a newline by using System.out.println();.
Alternatively, System.out.print(System.lineSeparator()); produces the same result.
Q2. Can mixing print and println cause unexpected line breaks?
A2.
Yes. Since print does not add a newline and println does, output order may result in line breaks appearing in unexpected places. Be mindful of structure and sequence.
Q3. What is the difference between printf and String.format?
A3.printf outputs directly to standard output, while String.format returns a formatted string. This allows the result of String.format to be stored, reused, or written to logs or files.
Q4. Can non-ASCII characters be displayed correctly with printf?
A4.
Non-ASCII strings can be printed using %s, but width specifiers (such as %10s) may cause misalignment because such characters often occupy more display width. Results may vary depending on fonts and editors.
Q5. How can I control the number of decimal places for numeric output?
A5.
Use format specifiers such as %.2f to control decimal precision.
double value = 12.3456;
System.out.printf("%.2f\n", value); // → 12.35Q6. How can I display array or list contents clearly?
A6.
Use Arrays.toString() for arrays and System.out.println(list) for lists.
int[] nums = {1, 2, 3};
System.out.println(Arrays.toString(nums));Q7. What should I do with print statements before production release?
A7.
Remove unnecessary print or println statements, or replace them with a logging framework such as Logger or Log4j to avoid information leakage and performance issues.
Q8. How can I save output to a file?
A8.
You can write formatted strings to a file using FileWriter or BufferedWriter. Using String.format beforehand is especially convenient.


