Course outline · 0% complete

0/29 lessons0%

Course overview →

Printing, comments, and escapes

lesson 1-3 · ~7 min · 3/29

print vs println

Printing is how a program reports its results, and it is also how you will pass every exercise in this course: the checker compares your output character for character, so controlling exactly what appears — and where the line breaks fall — matters from day one. (Working engineers live in printed output too: server logs are millions of print statements.) Java gives you two printing tools:

  • System.out.println(x) prints x and then moves to the next line.
  • System.out.print(x) prints x and stays on the same line.

Comments work like this:

// single line comment, like Python's #
/* multi-line comment,
   like Python's triple quotes */

You can glue text and values together with +, the way you used + on strings in Python:

System.out.println("score: " + 42);

Code exercise · java

Predict the output before you run: three print calls followed by one println. How many lines will appear?

The + gotcha

+ means numeric addition between two numbers, but joining when either side is a String. Java evaluates left to right, so what happens depends on where the String enters the expression:

System.out.println("sum: " + 1 + 2);   // sum: 12
System.out.println("sum: " + (1 + 2)); // sum: 3
System.out.println(1 + 2 + " apples"); // 3 apples

In the first line, "sum: " + 1 joins into the String "sum: 1", and then + 2 joins again. Parentheses force the addition to happen first while both sides are still numbers. This bites real programs constantly — wrap arithmetic in parentheses whenever it shares a line with text.

Code exercise · java

Predict all three lines before running: which prints 12, which prints 3, and why does the last one add correctly without parentheses?

Escape sequences

Inside a string, a backslash starts an escape sequence, a stand-in for a character you cannot type directly:

EscapeMeaning
\nnew line
\ttab
\"a literal double quote
\\a literal backslash

So System.out.println("a\nb") prints a and b on separate lines, exactly like Python's \n.

Quiz

What does System.out.print("x\ty") produce?

Code exercise · java

Your turn. Using a single println and escape sequences, print two lines where each label is followed by a tab: `Name:` tab `Grace`, then `Role:` tab `Engineer`.