java-foundations Lesson 1 15 min read

Console Output

println, print, escape sequences, and making your program speak

Reading: Reges & Stepp: Ch. 1 §1.3–1.4

Quick check before you start: Do you know what System.out.println() does? If yes, skip to println vs print: The Newline Question.

Practice this topic: Output matching exercises in Lab 1

After this lesson, you will be able to:

  • Use println() and print() to control where newlines appear
  • Apply escape sequences (\n, \t, \\, \") to embed special characters in output
  • Combine strings and values using concatenation with +
  • Write single-line and multi-line comments in Java
  • Use printf() for formatted output with precise control

Why Precise Output Matters

In the previous lesson you printed “Hello, World!” to the console. That was one line. But in the real world, programs need to communicate results clearly — a receipt with aligned columns, a log file with timestamps, a data export with commas in the right places.

If your output does not match the expected format, automated graders reject it, users get confused, and other programs cannot parse your data.

Output is also your most powerful debugging tool. When your program is not working, the fastest way to figure out what is going wrong is to print the values of your variables at key points.


println vs print: The Newline Question

You already know System.out.println() — it prints text and then moves the cursor to the next line. But Java also offers System.out.print(), which prints text and does not move to the next line.

System.out.println("Hello");   // prints "Hello", then moves to next line
System.out.print("Hello");     // prints "Hello", cursor stays on same line

The difference is that newline at the end. println stands for “print line” — it finishes the line and starts a new one.

Seeing the Difference

Consider this program:

public class Output {
    public static void main(String[] args) {
        System.out.print("A");
        System.out.print("B");
        System.out.print("C");
        System.out.println();      // just a newline, no text
        System.out.println("D");
    }
}

Output:

ABC
D

The first three print() calls place “A”, “B”, and “C” on the same line because none of them add a newline. Then println() with no arguments outputs a blank newline. Finally, println("D") prints “D” on line 2.

When to Use Each

Method Use When…
println(text) You want to print a complete line (most common)
print(text) You are building a line piece by piece across multiple statements
println() You want to output a blank line

Key insight: println = print + newline. print = print only, no newline. Most of the time, you want println. Use print when you are building a single line across multiple statements.


Check Your Understanding
What does this program print?
AA on one line, B on another, C on another
BABC on one line, D on the next
CAll on one line: ABCD
DNothing — it will not compile
Answer: B. print("A") and print("B") build "AB" on the first line. Then print("C") adds "C", making "ABC". Then println("D") prints "D" on the next line.
public class Output {
    public static void main(String[] args) {
        System.out.print("A");
        System.out.print("B");
        System.out.println("C");
        System.out.println("D");
    }
}

</div>


Escape Sequences: Special Characters Inside Strings

What if you want a newline in the middle of your output? Or a tab for alignment? Or a literal double-quote character inside a string?

You cannot just type these directly. A newline in your source code does not become a newline in the output. A double-quote would end the string prematurely.

The solution: escape sequences. A backslash followed by a specific character gives it special meaning.

The Essential Escape Sequences

Sequence Name What It Does
\n Newline Moves cursor to the next line
\t Tab Moves cursor to next tab stop (typically 4-8 spaces)
\\ Backslash Prints a literal backslash
\" Double quote Prints a literal double-quote inside a string

Newline: \n

The newline escape sequence lets you produce multiple lines from a single println() call:

public class NewlineExample {
    public static void main(String[] args) {
        System.out.println("Line 1\nLine 2\nLine 3");
    }
}

Output:

Line 1
Line 2
Line 3

Tab: \t

Tabs are useful for rough column alignment:

public class TabExample {
    public static void main(String[] args) {
        System.out.println("Name\tAge\tGPA");
        System.out.println("Alice\t25\t3.8");
        System.out.println("Bob\t23\t3.5");
    }
}

Output:

Name    Age     GPA
Alice   25      3.8
Bob     23      3.5

Watch out: Tab stops are not guaranteed to produce perfectly aligned columns. For precise alignment, use printf (covered later). For rough alignment in practice problems, tabs are fine.

Backslash: \\

Because backslash starts an escape sequence, you need two to print one:

public class BackslashExample {
    public static void main(String[] args) {
        System.out.println("File path: C:\\Users\\Alice\\Documents");
    }
}

Output:

File path: C:\Users\Alice\Documents

Double Quote: \"

Double quotes delimit strings. To include a literal quote inside, escape it:

public class QuoteExample {
    public static void main(String[] args) {
        System.out.println("She said \"Hello!\"");
    }
}

Output:

She said "Hello!"

Without the backslashes, the compiler would see "She said " as a complete string, followed by invalid Java.

The trick: If a string ends unexpectedly in your editor (strange syntax highlighting), you probably forgot to escape a quote inside the string.


Check Your Understanding
What does this print?
AX on one line, Y on another
BX\nY on one line (the \n is literal text)
CX on one line, Y on the next
DNothing — it will not compile
Answer: C. \n is the escape sequence for newline, so it splits the output across two lines.
public class Output {
    public static void main(String[] args) {
        System.out.println("X\nY");
    }
}

</div>


String Concatenation with +

In Java, the + operator does double duty. Between two numbers, it adds. But if either operand is a String, + performs concatenation — it joins pieces into a single string.

System.out.println("Hello" + " " + "World");    // Hello World
System.out.println("Score: " + 95);              // Score: 95
System.out.println("GPA: " + 3.85);             // GPA: 3.85

When Java sees "Score: " + 95, it converts 95 to the String "95" and concatenates.

The Parentheses Trap

Concatenation evaluates left-to-right, which can bite you:

public class ConcatTrap {
    public static void main(String[] args) {
        System.out.println("Total: " + 5 + 3);    // Total: 53 (not 8!)
        System.out.println("Total: " + (5 + 3));  // Total: 8 (parentheses first)
    }
}

In the first line, Java evaluates left to right: "Total: " + 5 gives "Total: 5", then "Total: 5" + 3 gives "Total: 53".

In the second line, parentheses force 5 + 3 to evaluate as integer addition first (giving 8), then concatenation.

Watch out: When mixing strings and numbers with +, use parentheses around arithmetic that should happen before concatenation.


Comments: Notes for Humans

Comments are text that the compiler completely ignores. They exist to help humans understand the code.

Single-Line Comments

// This is a comment. The compiler ignores it.
System.out.println("Hello");  // This comment is at the end of a line

Multi-Line Comments

/* This comment spans
   multiple lines.
   The compiler ignores all of it. */
System.out.println("Hello");

What to Comment

Good comments explain why you did something, not what the code does. The code itself tells the reader what is happening.

// BAD: States the obvious
int total = price + tax;  // add price and tax

// GOOD: Explains the reasoning
int total = price + tax;  // Tax includes 8% state + 2% local

For this course, include a comment at the top of every file with your name, the date, and a brief description of the program’s purpose.


printf(): Formatted Output

Java provides a third output method: System.out.printf() (print formatted). It gives you precise control over how numbers display.

Basic Syntax

System.out.printf(formatString, value1, value2, ...);

The format string is a template with placeholders starting with %:

public class PrintfExample {
    public static void main(String[] args) {
        String name = "Alice";
        int age = 25;
        double gpa = 3.456789;

        System.out.printf("Name: %s, Age: %d%n", name, age);
        System.out.printf("GPA: %.2f%n", gpa);
    }
}

Output:

Name: Alice, Age: 25
GPA: 3.46

Common Format Specifiers

Specifier Type Example
%d Integer printf("%d", 42)42
%f Float printf("%f", 3.14)3.140000
%.2f Float, 2 decimals printf("%.2f", 3.14159)3.14
%s String printf("%s", "Hi")Hi
%n Newline Platform-independent line break

Watch out: printf does NOT add a newline automatically. You must include %n or \n at the end if you want to advance to the next line.

Why Use printf?

For simple output, println with concatenation works fine. But printf shines when you need:

  • Fixed decimal places: %.2f always shows exactly 2 decimals — essential for prices
  • Column alignment: %10d right-justifies in a 10-character field
  • Clean templates: The format string reads like a template with holes
public class PriceExample {
    public static void main(String[] args) {
        double price = 19.9;
        System.out.printf("Price: $%.2f%n", price);
        // Output: Price: $19.90 (with trailing zero!)

        System.out.println("Price: $" + price);
        // Output: Price: $19.9 (no trailing zero — looks unprofessional)
    }
}

A Simple Receipt

Let us combine everything into something real:

public class Receipt {
    public static void main(String[] args) {
        System.out.println("===== Receipt =====");
        System.out.println("Item\tPrice");
        System.out.println("----\t-----");
        System.out.println("Milk\t$3.99");
        System.out.println("Eggs\t$2.49");
        System.out.println("Bread\t$2.99");
        System.out.println("-------------------");
        System.out.println("Total\t$9.47");
    }
}

Output:

===== Receipt =====
Item    Price
----    -----
Milk    $3.99
Eggs    $2.49
Bread   $2.99
-------------------
Total   $9.47

Six println() calls, but it works and is clear. Once you learn loops, you will generate this kind of output dynamically from data.


What you learned

  • println() vs print(): println adds a newline; print does not. Use println for complete lines.
  • Escape sequences: \n for newline, \t for tab, \\ for literal backslash, \" for literal quote.
  • String concatenation: Use + to join strings and values. Watch out for the left-to-right evaluation trap.
  • Comments: Use // for single-line, /* */ for multi-line. Comment the why, not the what.
  • printf(): Format specifiers give you precise control over numbers and alignment.

What Comes Next

Next: variables — named storage locations. Everything is hardcoded right now; variables let your programs work with dynamic data.