Printing output
On This Lesson 11 topics
Lesson Overview
So far every program you wrote printed something, but we treated System.out.println(...) as a magic phrase. This lesson explains it. You will learn the difference between print and println, how to print text and numbers, how to join several pieces into one line with +, and how to include a new line, a tab, or a quotation mark inside text.
In the recipe-card picture, printing is the card's output: the finished dish you put on the table. Text in quotes is a label you write by hand. A number is a measured amount. The + is the cook combining a label and an amount on one line of the card.
Why this matters: output is how a program shows what it did. In backend work, the same skill produces log lines and console messages that you read when something breaks. A program you cannot see inside is a program you cannot debug.
This lesson builds on Lessons 1 and 2: you know where statements go and that each ends with a semicolon.
Learning Objectives
By the end of this lesson you will be able to:
- Explain the difference between
System.out.printandSystem.out.println. - Print text, whole numbers, and decimal numbers.
- Explain why text needs double quotes and numbers do not.
- Join text and values with
+, and predict the result. - Use
\n,\t,\", and\\inside text. - Write a short program that prints a multi-line, aligned layout.
Written Explanation
The statement, word by word
System.out.println("Hello");Read it from left to right. System is a built-in class that comes with Java. out is a thing inside it that stands for the standard output, usually your terminal or the IDE's output panel. println is a method, a named action, that writes to it. The parentheses hold what to write. The dots connect the names, and the semicolon ends the statement.
You will not need to build anything like System.out yourself in this module. Use it as a fixed phrase, like main. Remember that it is case sensitive: a capital S in System and lowercase out.
println and print
The official documentation for PrintStream, the type of System.out, says println behaves as if it first calls print with the value and then ends the line. So the only difference is the line ending:
System.out.println(x)writesxand moves to a new line.System.out.print(x)writesxand stays on the same line.
System.out.print("Name: ");
System.out.println("Ana");
System.out.println("Age: " + 30);Output:
Name: Ana
Age: 30The first statement leaves the cursor right after Name: . The second continues on the same line and then ends it. The third starts a new line.
Calling println() with nothing in the parentheses ends the current line and prints nothing else. Use it to make an empty line:
System.out.print("A");
System.out.print("B");
System.out.println();
System.out.println("C");prints AB on the first line and C on the second.
One detail: the line ending that println writes comes from the system's line separator, which is not the same on every operating system. You will not notice it on screen, but a file written on Windows may differ in invisible characters from one written on Linux.
Text and numbers
Text, which Java calls a string, is written in double quotes. Everything between the quotes is printed exactly, including spaces:
System.out.println("Hello, world"); // prints: Hello, world
System.out.println("a b"); // prints: a b (three spaces)Numbers are written without quotes:
System.out.println(42); // prints: 42
System.out.println(3.5); // prints: 3.5The quotes matter. "42" is text that happens to look like a number, and 42 is a number. Both print the same here, but they behave differently once we start calculating in later modules. System.out.println(true) also works and prints true. Which kinds of values Java has, and what they can do, is the subject of the next module.
What about text without quotes? System.out.println(Hello); makes the compiler look for something named Hello, not find it, and report cannot find symbol. Quotes are how you tell Java "this is words, not a name."
Joining with +
When one side of + is text, Java turns the other side into text and joins them:
System.out.println("Age: " + 30); // Age: 30You can chain several pieces:
System.out.println("Total: " + 3 + " items"); // Total: 3 itemsBe careful with spaces: Java joins exactly what you give it. The space after Total: and the space before items are inside the quotes, and they are what separates the pieces on screen.
Here is a trap. When both sides of a + are numbers, Java adds them. The expression is evaluated from left to right:
System.out.println("Total: " + 3 + 4); // Total: 34
System.out.println("Total: " + (3 + 4)); // Total: 7
System.out.println(3 + 4 + " items"); // 7 itemsThe first prints Total: 34: after "Total: " + 3 becomes text, the + 4 joins again. The second adds the numbers first because of the parentheses. The third adds 3 + 4 before the text appears, because it is evaluated left to right. If you want to be sure, use parentheses around arithmetic.
Special characters inside text
Some characters are hard to type in the middle of a string, so Java uses a backslash \ followed by a letter or symbol. This pair is called an escape sequence. The Java Language Specification lists the allowed ones. These four cover most of what you need now:
| Write this | You get | Example |
|---|---|---|
\n | A new line | "Line one\nLine two" prints on two lines |
\t | A tab (a jump to the next column) | "Tea\t5" |
\" | A double quote that does not end the text | "She said \"hi\"" |
\\ | One backslash | "C:\\temp" prints C:\temp |
Any other letter after a backslash is a compile-time error. A string literal also may not contain a real line break between its quotes, so "Line one followed by a line break and Line two" does not compile. Use \n instead.
\n lets you do with one print what println does for you. These two statements print the same thing:
System.out.println("Done");
System.out.print("Done\n");(The first one uses your system's line separator, which can differ from \n on some systems, so prefer println for ordinary lines.)
Examples
Example 1: print versus println (simple)
public class Pr {
public static void main(String[] args) {
System.out.print("Name: ");
System.out.println("Ana");
System.out.println("Age: " + 30);
System.out.println(3 + 4);
System.out.println("3 + 4");
}
}Output:
Name: Ana
Age: 30
7
3 + 4The last two lines show the difference between numbers and text. 3 + 4 without quotes is a calculation, and "3 + 4" with quotes is just characters.
Example 2: a small receipt (practical)
public class Rcpt {
public static void main(String[] args) {
System.out.println("=== Receipt ===");
System.out.print("Tea");
System.out.print("\t");
System.out.println(5);
System.out.print("Cake");
System.out.print("\t");
System.out.println(12);
System.out.println("Total:\t" + (5 + 12));
System.out.println("Thank you!");
}
}Output:
=== Receipt ===
Tea 5
Cake 12
Total: 17
Thank you!Each tab jumps to the next tab stop, so the numbers line up in a column in most terminals. The exact width of a tab depends on the terminal or editor, so alignment can differ slightly from what you see here.
Example 3: escapes in a realistic message (realistic)
Programs often print messages that include quotation marks or file paths. Here is one that does both:
public class Msg {
public static void main(String[] args) {
System.out.println("Config file: C:\\app\\config.txt");
System.out.println("Status: \"OK\"");
System.out.println("Line one\nLine two");
}
}Output:
Config file: C:\app\config.txt
Status: "OK"
Line one
Line twoWithout the doubled backslashes, \a in \app would be an invalid escape and the file would not compile. Without \" the quotes around OK would end the text early.
Backend Insight
When a backend service runs on a server, nobody is watching a window. The way you learn what it did is through log lines, which are text messages written to the console or to a file, usually with a timestamp and a short description. Real services use a logging library, which you will meet later, rather than System.out. But the habit is the one you are building now: print the right fact, in a readable form, with the value next to its label, like "Order id: " + 42.
Two lessons from this one carry over directly. First, a message must be easy to read at 3 a.m., so labels and consistent layout matter. Second, text that joins values can be built wrongly, as in the "Total: " + 3 + 4 trap, and logs that print the wrong number mislead everyone reading them.
Common Mistakes
Mistake 1: Forgetting the quotes
- Incorrect:
System.out.println(Hello);(compiler:cannot find symbol) - Correct:
System.out.println("Hello");
Mistake 2: Expecting print to start a new line
If you use print three times, all the text appears on one line. Use println, or add \n, when you want separate lines.
Mistake 3: Joining a number after text when you wanted to add
- Incorrect:
"Total: " + 3 + 4printsTotal: 34 - Correct:
"Total: " + (3 + 4)printsTotal: 7
Mistake 4: Single quotes for text
- Incorrect:
System.out.println('Hello'); - Correct:
System.out.println("Hello");
Single quotes are for a single character, which is a separate idea. Text of several characters needs double quotes, and the compiler will report an unclosed character literal.
Mistake 5: A single backslash in a path
- Incorrect:
"C:\temp"(the\tbecomes a tab) - Correct:
"C:\\temp"
Exercises
Try each exercise yourself before opening the solutions. Hands-on items must be done on your machine.
Level A: Foundation
A1. What is the single difference between print and println?
Show solution A1
A1. println ends the line after printing and print does not.
A2. What does each line print? (a) System.out.println("Hi " + "there"); (b) System.out.println(2 + 3); (c) System.out.println("2 + 3");
Show solution A2
A2. (a) Hi there. (b) 5. (c) 2 + 3.
A3. Which escape sequence gives you (a) a new line, (b) a tab, (c) a double quote inside text?
Show solution A3
A3. (a) \n. (b) \t. (c) \".
Level B: Application
B1. Write a program, Intro, that prints exactly this, using only print for the first line and println for the second:
City: Cairo
DoneShow solution B1
B1.
public class Intro {
public static void main(String[] args) {
System.out.print("City: Cairo\n");
System.out.println("Done");
}
}This prints the two lines. The first statement must use print, so the line break comes from \n inside the text. (Printing "City: " and "Cairo\n" as two print calls is also fine.)
B2. Predict the output of each statement, then run to check: (a) System.out.println("Count: " + 1 + 2); (b) System.out.println("Count: " + (1 + 2)); (c) System.out.println(1 + 2 + " items");
Show solution B2
B2. (a) Count: 12. (b) Count: 3. (c) 3 items.
B3. Write a program that prints one println statement producing this two-line output, using \n once:
Line one
Line twoShow solution B3
B3.
public class Lines {
public static void main(String[] args) {
System.out.println("Line one\nLine two");
}
}Level C: Challenge
C1. Write a program, Menu, that prints this price list so the second column lines up using tabs, with the title in its own line. Items and prices: Tea 5, Cake 12, Juice 8.
Show solution C1
C1. For example:
public class Menu {
public static void main(String[] args) {
System.out.println("Price list");
System.out.println("Tea\t5");
System.out.println("Cake\t12");
System.out.println("Juice\t8");
}
}Output (tab widths vary by terminal): Price list, then Tea, Cake, Juice with the prices lined up in a column. With names of different lengths, such as Cake and Juice, tabs may not align perfectly in every terminal, which is a limit of tabs.
C2. The program below fails to compile. Without running it, list every problem and fix them all:
public class Broken {
public static void main(String[] args) {
System.out.println('Path: ' + "C:\data");
System.out.println(Total: + 5 + 6);
}
}Show solution C2
C2. Problems: (1) 'Path: ' uses single quotes, so the compiler reports an unclosed character literal; use double quotes. (2) "C:\data" has \d, an invalid escape; write "C:\\data". (3) Total: is not in quotes, so it is invalid; write "Total: ". Also, + 5 + 6 after text joins the numbers one by one and would print Total: 56; if the sum 11 is wanted, use (5 + 6). A corrected version:
public class Broken {
public static void main(String[] args) {
System.out.println("Path: " + "C:\\data");
System.out.println("Total: " + (5 + 6));
}
}It prints Path: C:\data and then Total: 11.
Mini Challenge
Create a program named Card that prints a business card of your own with four lines: a name, a role, an email address, and a phone number. Put a label before each value using print for the label and println for the value on every line, and add a top and bottom border line made of repeated characters, for example ==========. Do not use real private data; invent a phone number and email.
Check your work: it compiles, there are exactly six lines of output, each label and value sit on the same line, and your own borders use println. This is the core of the module's lab.
Summary & Next Lesson
Key takeaways
printlnprints and moves to a new line.printprints and stays on the same line.- Text goes in double quotes. Numbers are written without quotes.
+joins when one side is text, and adds when both sides are numbers. Evaluation goes left to right, so use parentheses for sums inside text.- Escape sequences
\n,\t,\", and\\put special characters inside text. - A real line break inside a string literal is a compile-time error.
Next lesson
You can now make the program show things. Next, "Comments" teaches how to leave notes in the code for people: single-line, multi-line, and Javadoc comments, and how to write ones that help.
Self-check
- What does
System.out.print("A"); System.out.print("B");print? - What is the output of
"x" + 1 + 2? - Why does
System.out.println(Hello);fail? - How do you print a double quote inside text?
- How do you print
C:\logs?
Show answers
ABon a single line.x12.- Without quotes, Java looks for something named
Helloand cannot find it. It needs"Hello". - Put a backslash before it:
\". System.out.println("C:\\logs");
References
- Oracle,
PrintStreamAPI, Java SE 21. It saysprintln(String)behaves likeprint(String)followed byprintln(), thatprintln()writes the line separator, and that the separator comes from theline.separatorsystem property. - Oracle, The Java Language Specification, Java SE 21, section 3.10.5 (String Literals). It lists the escape sequences, says other characters after a backslash are errors, and says a raw line break inside a string literal is an error.
- The outputs shown, including
Total: 34for"Total: " + 3 + 4, were produced by compiling and running the examples with JDK 21. The left-to-right rule for+is described here from that run and not read from the specification's section on the additive operators.
Practice
Apply this lesson with the module's lab, exercises and quiz.
Marking a lesson complete is optional and you can undo it any time. Your progress stays in this browser.