Output Statements
How Java programs display information: the difference between print and println, how values of each type appear, how the + operator joins text, and how to predict output exactly.
Output is how a program communicates its results. In Java, System.out.print and System.out.println display information on the computer's display. The only difference between them is what happens afterward: println moves the cursor to a new line after displaying its information, while print does not. Predicting output exactly, character by character and line by line, is one of the most important skills in reading code, because it shows whether you truly understand what each statement does.
1Displaying Output
When a Java program runs, text sent to System.out appears in a console window. Think of the console as a page with an invisible cursor that marks where the next character will appear. Every output statement writes its text at the cursor, and the cursor moves along as characters are written.
An output statement has the form System.out.println(value);. Inside the parentheses you can place a literal, a variable, or any expression. Java evaluates the expression first and then displays the resulting value. That means System.out.println(3 + 4) displays 7, while System.out.println("3 + 4") displays the characters 3 + 4 exactly as typed, because they are inside a string literal.
Output statements run in sequence like all other statements. If an earlier statement prints something, nothing later in the program can take it back or change its position, so the order of output statements determines the order of what appears on the screen.
The name System.out.println itself describes what happens. System is a class that is always available to Java programs; out is an object inside it that represents the standard output stream, usually the console; and println is a method of that object. The dots connect these parts, the same way later code will call methods on objects such as strings and lists. You do not need to create System.out yourself; it is ready to use in every program.
println, an expression is evaluated first and its value is displayed; anything inside double quotes is displayed exactly as typed.2print and println
System.out.println displays its value and then moves the cursor to the beginning of the next line. The next piece of output therefore starts on a fresh line. System.out.print displays its value and leaves the cursor exactly where the text ended, so the next output continues on the same line.
Calling System.out.println() with nothing inside the parentheses displays no text but still moves the cursor to the next line. It is useful for ending a line that was built with print or for leaving a blank line between sections of output. System.out.print() with empty parentheses, by contrast, does not compile, because print requires something to display.
print leaves the cursor right after the text it displays, so the next output continues on the same line. println displays its text and then moves the cursor to the start of a new line.| Statement | What it displays | Where the cursor ends up |
|---|---|---|
System.out.print(x); | The value of x | Right after the text, on the same line |
System.out.println(x); | The value of x | At the start of the next line |
System.out.println(); | Nothing | At the start of the next line (ends the current line) |
Predicting Line Breaks
Predict the exact output, including where each line ends.
System.out.print("Ready");
System.out.print(" set");
System.out.println(" go!");
System.out.println("Race started");
Ready set go!
Race started
- 1First two statements.
printdisplays "Ready" and then " set" on the same line; neither moves the cursor down. - 2Third statement.
printlnadds " go!" to the same line, then ends the line. - 3Fourth statement. "Race started" begins on the new line.
Ready set go! and Race started. A line ends only when a println runs.When predicting output, keep track of the cursor after every statement. A print followed by a println puts both pieces of text on the same line; the line break comes after the println's text, not before it. Writing the output one character at a time, with the cursor marked, avoids almost every line-break mistake.
3How Values Are Displayed
Each type of value has a standard printed form. An int prints as a plain whole number. A double always prints with a decimal point, so a double holding twelve prints as 12.0. A boolean prints as the word true or false. A String prints its characters without the surrounding quotation marks, which are only part of how the literal is written in code.
Because expressions are evaluated before printing, the type of the expression's result decides the format. System.out.println(7 / 2) prints 3, an int, while System.out.println(7 / 2.0) prints 3.5. Some double results print with many digits, such as 0.30000000000000004 for 0.1 + 0.2, a consequence of round-off error in how computers store real numbers.
| Value type | Example value | Printed as |
|---|---|---|
int | 17 | 17 |
double | 17.0 | 17.0 |
double | 2.5 | 2.5 |
boolean | false | false |
String | "hi" | hi (no quotes) |
Printing Different Types
Predict how each value is displayed.
int laps = 8;
double pace = 6.5;
boolean finished = true;
double whole = 12;
System.out.println(laps);
System.out.println(pace);
System.out.println(finished);
System.out.println(whole);
System.out.println(laps / 3);
8
6.5
true
12.0
2
- 1Each value prints in its type's normal form. An
intprints without a decimal point; adoublealways includes one; abooleanprints the wordtrueorfalse. - 2
wholeis a double. Even though it was assigned 12, it holds 12.0 and prints that way. - 3Expressions are evaluated first.
laps / 3is integer division, 8 / 3 = 2, and only the result is printed.
8, 6.5, true, 12.0, and 2. println displays the value of whatever expression it receives.4Joining Text With +
Output usually combines labels with values: "Score: 95." The + operator joins (concatenates) a String with another value, converting the other value to text first. "Score: " + 95 becomes "Score: 95".
The catch is that + also means addition, and Java decides which meaning to use one operator at a time, left to right. While both operands are numbers, + adds. As soon as one operand is a String, + joins, and the result is a String, so every later + in the expression also joins. Parentheses change the order: anything inside them is evaluated first, so "Sum: " + (4 + 5) adds before joining.
Concatenation never adds spaces. Any space you want in the output must appear inside a string literal, typically at the end of a label ("Total: ") or the start of the text that follows a value (" points").
String appears on the left, each following + joins text. Parentheses force the numbers to be added first.| Expression | Value | Why |
|---|---|---|
"A" + 1 + 2 | "A12" | The String comes first, so every + joins text |
1 + 2 + "A" | "3A" | 1 + 2 is added before the String is reached |
"A" + (1 + 2) | "A3" | Parentheses evaluate first |
"" + 1 + 2 | "12" | An empty String turns the rest into joining |
"Pass: " + true | "Pass: true" | A boolean joins as the word true |
The Left-to-Right Trap
Predict each line.
System.out.println("Sum: " + 4 + 5);
System.out.println("Sum: " + (4 + 5));
System.out.println(4 + 5 + " is the sum");
System.out.println(1 + 2 + "3" + 4 + 5);
Sum: 45
Sum: 9
9 is the sum
3345
- 1Line 1.
"Sum: " + 4is the string "Sum: 4"; adding 5 joins text again: "Sum: 45". - 2Line 2. Parentheses make
4 + 5evaluate first, so the output is "Sum: 9". - 3Line 3. Left to right,
4 + 5are bothintvalues, so they add to 9 before the string appears. - 4Line 4.
1 + 2is 3; then3 + "3"is "33"; after that every+joins text: "334", then "3345".
Sum: 45, Sum: 9, 9 is the sum, and 3345. Addition happens only until the first String; after that, + means join.Fixing Output That Runs Together
The output below looks wrong. Explain why and fix it.
int total = 42;
System.out.println("Total:" + total + "points");
Total:42points
- 1Concatenation adds nothing extra.
+joins text exactly as is; it never inserts spaces. - 2Put the spaces inside the string literals.
Fixed
int total = 42; System.out.println("Total: " + total + " points");OutputTotal: 42 points
"Total: " and the start of " points" produces Total: 42 points.In "Total: " + 2 + 3, the result is "Total: 23", not "Total: 5". Once the expression contains a String on the left, each later + joins text. Put arithmetic in parentheses whenever it appears after a label.
"Name:" + name produces Name:Ivy. The + operator joins text exactly, with no spacing of its own. Check each boundary between a literal and a value and decide whether a space belongs there.
5Building a Line From Several Statements
A single line of output can come from several statements: a series of print calls followed by one println (or an empty println()) to finish the line. This is handy when parts of a line are computed at different times, and it becomes essential when output is produced inside loops later on.
To predict the output of such code, trace it as a list of characters with a cursor. Each print appends text; each println appends its text and then a line break. The final output is simply the text accumulated in that order.
println runs; println() with nothing inside prints an empty line.One Line From Several Statements
A program prints a player's stats. Predict the output.
int goals = 7;
int assists = 4;
System.out.print("Goals: " + goals);
System.out.print(", Assists: " + assists);
System.out.println();
System.out.println("Points: " + (goals + assists));
Goals: 7, Assists: 4
Points: 11
- 1Two
printcalls build line 1. "Goals: 7" then ", Assists: 4" on the same line. - 2
println()with no argument ends that line without adding text. - 3Line 2. The parentheses add 7 + 4 = 11 before joining it to "Points: ".
Goals: 7, Assists: 4 followed by Points: 11. Empty println() is a clean way to end a line built with print.6Designing Readable Output
Output is written for people, so it should be clear without reading the code. Label every value ("Average: 87.5" rather than "87.5"), keep one idea per line, and use blank lines to separate groups of information. Computed values should come from the program's variables and expressions, never from numbers typed by hand into the output text, so that the output stays correct if the data changes.
When output looks wrong, compare it with the expected output character by character. Missing spaces, numbers that were joined instead of added, and lines that run together are among the most common output bugs, and each has a simple cause: a missing space in a literal, missing parentheses around arithmetic, or a print where a println was needed.
Output is also the main tool for checking a program's work. While developing, programmers often add temporary statements that print intermediate values, such as a running total after each step, to see exactly what the program is doing. Once the program behaves correctly, those debugging lines are removed so the final output stays clean. Printing a label with each debugging value ("total after step 2: " + total) makes it obvious which value is which.
Printing a Simple Receipt
Write statements that print a three-line receipt for 3 notebooks at 2.25 each, with a total line computed by the program.
int qty = 3;
double price = 2.25;
System.out.println("Item: notebook");
System.out.println("Qty: " + qty + " @ " + price);
System.out.println("Total: " + (qty * price));
Item: notebook
Qty: 3 @ 2.25
Total: 6.75
- 1Label every value. Output is for people; "6.75" alone means nothing, "Total: 6.75" does.
- 2Compute in the program. The total is
qty * price, wrapped in parentheses so it is multiplied before being joined to the label. - 3One
printlnper line. Each statement produces exactly one complete line, which keeps the code easy to match with the output.
Item: notebook, Qty: 3 @ 2.25, and Total: 6.75.Writing System.out.println("Total: 6.75"); produces the right text today, but the moment the quantity or price changes, it becomes wrong. Always print the variable or expression that computes a value, so the output and the data can never disagree.
Four Habits for Predicting Output
1. Track the Cursor
print stays on the line; println ends it after its text.
2. Evaluate, Then Display
Work out the value of the expression before deciding what prints.
3. Left to Right for +
Numbers add until a String appears; after that, + joins text.
4. Check Every Space
Spaces come only from inside string literals.
System.out.print and System.out.println display information on the computer display. System.out.println moves the cursor to a new line after the information has been displayed, while System.out.print does not. The value inside the parentheses is evaluated first, and each type prints in its standard form. The + operator joins a String with other values, evaluated left to right, so parentheses are needed to add numbers after a label, and every space must come from inside a string literal.