Java Output and Comments
Make your program's results easy to read. Learn when to continue a line, when to finish it, how to format a value, and how to write comments that explain why the code works that way.
Prerequisite: Java Syntax and Your First Program. Keep the class and main structure intact while experimenting with the statements inside it. These complete examples use the existing Java 21 runner; expected output is a comparison target, not a substitute for running your code.
What you will be able to do
- Choose print, println, or printf for an intended output layout.
- Predict spaces, line endings, and text-versus-number results.
- Use simple format placeholders and escape sequences correctly.
- Write comments that explain intent without duplicating the code.
- Distinguish compiler errors, formatting failures, and incorrect output.
- Build a readable report and check it against an explicit contract.
Start with what the reader needs to see
Output is the information a program presents while it runs. For our command-line examples, System.out writes to standard output, which the lesson runner displays in its terminal panel. A useful report needs more than correct numbers: the reader needs labels, spacing, and a layout they can understand.
Imagine giving a student a study report. A bare 4 could mean four sessions completed, four tasks remaining, or a score. Tasks left: 4 tells the reader what the value represents. Before coding, write down the exact lines you want, including any blank lines. That small output contract gives you something concrete to test.
Printing does not automatically save a file, update an account, or return a result to another method. These examples display fixed information only. Later lessons will connect output to input and stored values; today we will make the presentation deliberate.
Use print when the next output should continue on the same line
System.out.print writes its argument without adding a line ending. The next output begins immediately after it. It does not insert a space between calls for you. In the example below, the space after Student: and the spaces around the vertical bar are characters explicitly included in the messages.
Trace the output as a cursor moving across a page. The first call writes the label and leaves the cursor after its trailing space. The second writes Mina. The third completes the line and ends it because it uses println. The last call therefore begins on the next line.
Try removing only the space after Student:. Predict the changed first line before running. Then change the second call from print to println and explain why the status message moves. These edits affect layout, not the number of Java statements in the source.
Main.java · Build one line in pieces
Predict the result, edit Main.java, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
Student: Mina | Ready
Next session: Java
Check the changed-layout prediction
Removing the label's trailing space gives Student:Mina | Ready. Changing the name's call to println puts the status text on a new line. The space at the beginning of that status message remains there, because a line break does not remove characters from the next String.
Use println to finish a line
System.out.println writes its argument and then ends the current line. With no argument, println() simply ends the current line. That is a convenient way to create one blank line between groups of information when the previous output already ended its line.
Two important things are separate: the line breaks you use to format source code and the line endings your running program writes. Putting two print statements on different source lines does not make them print on different output lines. The output operations and their arguments determine that.
In the example below, predict the blank line after the title. Remove the empty println call and run again. The report should now have the same words with one fewer blank line. Prefer intentional spacing instead of adding empty lines until the result happens to look right.
Main.java · Separate lines and a blank line
Predict the result, edit Main.java, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
Study report
Topic: Java output
Status: practising
Calculate before joining a number to a label
The plus sign can add numbers or join text. The first expression below adds two numeric values and prints 5. In the second, evaluation starts with text, then joins 2 and then 3, producing Tasks: 23. Those digits do not get added just because they appear after a label.
The third line puts the arithmetic in parentheses, making the intended calculation explicit before its result is joined to the label. This is a good beginner habit: separate the question of what value you want from the question of how you display it.
Change both numbers to 4 and 1. Predict all three lines, not only the correct-looking final line. The results should be 5, Tasks: 41, and Tasks: 5. A program can compile successfully while its message communicates the wrong calculation.
Main.java · Labels do not perform arithmetic
Predict the result, edit Main.java, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
5
Tasks: 23
Tasks: 5
Check the changed-number prediction
With 4 and 1, the numeric addition is 5. Starting with the text label instead joins the digits to produce Tasks: 41. Parenthesizing the addition produces Tasks: 5. Formatting cannot choose the intended arithmetic rule for you.
Use printf when you need a small formatting template
System.out.printf takes a format string followed by values to place into it. Read the first example as a template: put the student's text at %s and the whole-number count at %d. The values after the format string supply those pieces in order. %n ends the line; printf does not add a line ending automatically.
For a decimal value, %.2f displays two digits after the decimal separator. It formats how the value looks; it does not turn approximate floating-point arithmetic into exact decimal arithmetic. This example is a score display, not a design for handling money.
The decimal example supplies java.util.Locale.ROOT to make its decimal point predictable across different system locales. Treat that fully qualified name as a standard-library setting for now; packages and imports have their own lesson. A different intended locale may use a comma instead of a dot.
To print a literal percent sign in a format string, use %%. The progress line combines a %d value, a literal percent sign, and %n. Do not confuse formatting placeholders with normal println text: println does not replace %d with a number. Match the number and kinds of arguments to the template.
Main.java · A formatted progress summary
Predict the result, edit Main.java, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
Student: Mina | Sessions: 3
Average: 8.50
Progress: 75%
Represent special characters without breaking the String
A double quote normally ends a quoted String. To include one inside the message, write a backslash followed by a double quote. To display a backslash, write two backslashes in the source. Java reads each escape as part of the String value instead of treating it as the end of the text.
The example below prints a quotation, a Windows-style path as ordinary text, and three lines from one print call. The path is not opened or created. The newline escapes in the last String move the output to another line; they are not literal backslash-and-n characters in the displayed result.
Inside an ordinary String, backslash-n represents a newline and backslash-t a tab. Tab alignment depends on where the terminal's tab stops fall, so tabs are not a guarantee of neatly aligned columns. For portable formatted line endings in printf, prefer %n. Use println for a simple separate line.
Main.java · Quotes and backslashes in messages
Predict the result, edit Main.java, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
Mina said: "Keep practising"
Folder example: C:\study\java
Read
Predict
Run
Comments explain the intent, not the terminal output
A // comment continues to the end of the source line. A block comment begins with /* and ends with */ and can span several source lines. The comments in the example below explain a calculation choice and why the help message belongs at the end. They do not produce terminal output.
Comment markers inside a quoted String are text, not active comments. That is why the example can print a URL containing //. The same distinction applies to a message containing /*. First determine whether the characters belong to source syntax or to the String value being printed.
Block comments do not nest. If a block you want to disable already contains a block comment, wrapping another /* ... */ around it can leave broken source. Commenting out code is sometimes useful during a small experiment, but restore or remove the experiment afterward instead of keeping a growing archive of disabled code.
A documentation comment starts with /** and supports tools such as Javadoc for documenting declarations. This lesson does not generate API documentation; a regular comment is enough for our small main method. Learn the difference without adding a documentation block above every local statement.
Main.java · Comments explain the display rule
Predict the result, edit Main.java, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
Tasks left: 4
Help: ask your tutor
Reference: https://example.com/java
Write comments that help a future reader make a decision
A comment such as Print the student name immediately above a statement that clearly prints the student name adds little. A comment such as Show remaining work, not completed work explains a choice that could otherwise be misunderstood. Use names and clear code for obvious mechanics; use comments for intent, assumptions, and constraints.
An inaccurate comment is worse than a missing one. If you change a calculation or the order of a report, reread nearby comments too. A comment claiming that a value has been validated does not make validation exist. Describe only the behavior and rules actually implemented.
Never leave passwords, access tokens, or private customer information in comments. Comments are not executed as instructions, but they remain visible to anyone who can read the source. For this lesson, use invented names and fixed study data rather than real personal records.
Repair the calculation, then check the layout
The intended result has two lines: Study summary and Tasks left: 4. This starter has an arithmetic/type mistake and a layout mistake. Run it, repair the compiler error first, then compare the actual layout with the intended output.
Main.java · Repair the study summary
Predict the result, edit Main.java, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
Reveal the explained repair
The original label plus 6 creates text, and subtracting 2 from that text is not valid. Parenthesize 6 - 2 before joining its result to the label. Then change the first print to println so the second message starts on its own line. Fixing only compilation leaves both messages stuck together.
Main.java · Repaired study summary
Predict the result, edit Main.java, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
Study summary
Tasks left: 4
Independent lab: a readable study-session receipt
Create a small study-session receipt that another student can read without guessing what each value means. Use only fixed values here; no input, database, or saved progress is required.
- Print Study session receipt as a title, followed by one blank line.
- Build Student: Mina on one line using print for the label and println for the name.
- Show Sessions: 3 with printf and a whole-number placeholder.
- Show Average: 8.50 with two decimal places and a predictable decimal point.
- Show Tasks left: 4 by calculating 6 - 2, not by hard-coding the result.
- Include one useful comment explaining an intent or display rule. Predict the output before running.
Main.java · Your study receipt
Predict the result, edit Main.java, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
Show hints without the solution
Sketch the output first. Use println for the title and the blank line, print followed by println for the student line, %d for the session count, and %.2f with the explicit locale for the average. Put the remaining-task subtraction in parentheses.
Reveal the explained lab solution
Main.java · Study receipt solution
Predict the result, edit Main.java, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
Study session receipt
Student: Mina
Sessions: 3
Average: 8.50
Tasks left: 4
The empty println creates the intentional blank line. print leaves the student label unfinished until println adds the name and ends the line. Each printf ends with %n; the decimal call uses an explicit locale. The subtraction is evaluated before the result is joined to its label. The comment explains the stable-display choice and is absent from the output.
Test one change at a time
- Change Mina to Sami. Only the student line should change.
- Change the sessions argument from 3 to 4. Keep %d and compare the result.
- Change the average from 8.5 to 7.0. Predict Average: 7.00.
- Remove the empty println. The report should lose exactly one blank line.
- Edit or remove the useful comment. The printed report should stay the same.
Common mistakes and what to inspect
First decide whether the source failed to compile, the running program failed, or the report simply has the wrong appearance. Read the diagnostic and compare the output contract before changing unrelated code.
Words run together
print does not add spaces or line endings. Check the end of one argument and beginning of the next. Include a separating space in the text or finish the line with println, depending on the output you intended.
%d appears as text
Placeholders are interpreted by printf, not println. Check the chosen output method before changing the format string or the value.
IllegalFormatConversionException or MissingFormatArgumentException
These can occur at runtime even when the source compiles. A %d placeholder needs a compatible whole-number argument, and a placeholder needing a value must have one. Check the template and argument list together. Do not try to fix an argument mismatch by reinstalling Java.
An escape or quote breaks compilation
Check the backslashes and straight double quotes in the actual Java editor. A path such as C:\study\java must use escaped backslashes inside the Java literal. Avoid copying typographic quotes from a formatted document.
A comment hides a needed closing brace
A // comment hides everything after it on that source line. An unclosed block comment can absorb later source. Find the intended comment boundary, then match the remaining braces; do not add random braces to source that is still inside a comment.
Frequently asked questions
Does print save information permanently?
No. These calls write to standard output. A terminal, runner, or surrounding system may capture that stream, but the program has not implemented file storage or account persistence just by printing a message.
Is printf better than println?
Neither is always better. Use println for a simple complete line, print for controlled pieces of a line, and printf for an intentional formatting template. Choose the simplest operation that makes the desired report clear.
Can I use System.err.println for errors?
Yes. System.err is a separate standard error stream. This runner displays diagnostics separately from ordinary output internally and combines them for presentation, so do not depend on its panel to preserve the exact interleaving of both streams. For these exercises, use System.out for the requested report.
Can comments fix or protect broken code?
No. A comment can explain an assumption, but it does not validate data or enforce a rule. Comments are also not a place to hide secrets. Use a comment to help a reader understand correct behavior, not to claim behavior that is missing.
Remember the reader and the next maintainer
A report is clear when labels explain values and spaces and line endings are deliberate. Comments are clear when they explain a real choice or assumption and remain accurate after edits. Neither attractive formatting nor a confident comment proves a calculation is correct.
Next, we will give information meaningful names in the Variables and Constants lesson. For now, check that you can predict each report line, choose an output operation, and explain why a comment is useful.
Can you predict the report?
Answer all six questions, then read the explanations. Results are temporary on this page and do not save course progress.
References and related learning
The study-report examples, practice tasks, and explanations are original SovranCode material. These official references support the API and language rules.
- Java 21 PrintStream: print, println, and printf
- Java 21 Formatter reference
- Java 21 lexical structure: comments and escapes
- Java 21 standard output and standard error
Review Java syntax · Review JDK setup · Java course roadmap.
Last updated: