Print Output: Talking to the Console

Print Output: Talking to the Console in Java: Printing is how your program talks back to you.

Concept Explanation

Printing is how your program talks back to you. It is also your first and most reliable debugging tool — when something misbehaves, printing a value is often the fastest way to see why.

Java gives you three print methods on System.out:

System.out.println("Adds a newline after");   // most common
System.out.print("Stays on the same line");   // no newline
System.out.printf("Formatted: %d items%n", 5); // placeholders

Syntax or Core Structure

public class Printing {
    public static void main(String[] args) {
        System.out.println("Line one");
        System.out.println("Line two");

        System.out.print("A");
        System.out.print("B");
        System.out.println();          // ends the AB line

        int apples = 7;
        double price = 1.25;
        System.out.printf("%d apples cost %.2f%n", apples, apples * price);
    }
}

Common printf Placeholders

  • %d — whole number
  • %f — decimal (%.2f rounds to two places)
  • %s — text
  • %n — newline (portable; prefer it over \n)

Escape Sequences

  • \n newline, \t tab, \" a literal quote, \\ a literal backslash.

Joining Values

The + operator concatenates when either side is text:

String name = "Ada";
int age = 36;
System.out.println("Name: " + name + ", Age: " + age);

Watch the trap: "Total: " + 1 + 2 prints Total: 12, because both numbers are glued as text. Force the maths with parentheses: "Total: " + (1 + 2).


Common Mistakes

  1. Single quotes for text: 'Hello' is invalid. Text needs double quotes; single quotes are for one char.
  2. Forgetting ln: print leaves the cursor on the same line, so output runs together.
  3. Concatenation before addition: See the 12 trap above.

Best Practices

  • Use printf for money and reports: %.2f is far cleaner than manual rounding.
  • Prefer %n over \n: It emits the correct line ending on every platform.
  • Graduate past printing: Print statements are great for learning; real applications use a logger.

Practice Exercises

  1. The Receipt: Print a three-item shop receipt with aligned prices using printf and %.2f.
  2. The Shape: Use \n and \t inside a single println to draw a small triangle of stars.
  3. The Trap: Print "Sum: " + 5 + 3, then fix it with parentheses so it shows Sum: 8.