Java Print Methods Explained: print vs println vs printf with Examples

目次

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:

HelloJava

2-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
Java

2-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

SpecifierDescriptionExample
%dInteger (decimal)%d → 10
%fFloating-point number%f → 3.141593
%sString%s → “Java”

Specifying decimal places:

double pi = 3.14159;
System.out.printf("Pi is %.2f.", pi);

Output:

Pi is 3.14.
  • %.2f means 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: 0007

4-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 = 15

By 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 file

6-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
D

Tip:

  • Only println adds 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 1020

Correct example:

System.out.println("Total is " + (x + y));

Output:

Total is 30

Tip:

  • 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 (%d for integers, %f for floating-point numbers, %s for 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

MethodCharacteristicsMain Use Cases
System.out.printOutputs without a newlineContinuous output on the same line
System.out.printlnAutomatically adds a newlineLine-by-line output
System.out.printfFormatted output using specifiersTables, alignment, numeric formatting
String.formatReturns a formatted stringLogs, emails, file output

8-2. Choosing the Right Method

  • Simple display or debuggingprint, println
  • Readable tables or aggregated dataprintf
  • Reusable formatted strings or further processingString.format

8-3. Practical Advice

  • Start with println as the default and switch to print, printf, or String.format as 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.35

Q6. 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.