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 (%.2frounds to two places)%s— text%n— newline (portable; prefer it over\n)
Escape Sequences
\nnewline,\ttab,\"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
- Single quotes for text:
'Hello'is invalid. Text needs double quotes; single quotes are for onechar. - Forgetting
ln:printleaves the cursor on the same line, so output runs together. - Concatenation before addition: See the
12trap above.
Best Practices
- Use
printffor money and reports:%.2fis far cleaner than manual rounding. - Prefer
%nover\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
- The Receipt: Print a three-item shop receipt with aligned prices using
printfand%.2f. - The Shape: Use
\nand\tinside a singleprintlnto draw a small triangle of stars. - The Trap: Print
"Sum: " + 5 + 3, then fix it with parentheses so it showsSum: 8.