Formatting the Output
1. Three Ways (beginner order)
println (new line), print (same line), printf/format (controlled decimals, tables).
System.out.println("Hello"); // Hello + newline
System.out.print("Hi "); // no newline
System.out.print("there"); // → Hi there (same line)
System.out.printf("pi=%.2f%n", 3.14159); // pi=3.14
2. Format Specifiers (exam table)
| Spec | Meaning | Example → Output |
|---|---|---|
%d |
integer | printf("%d", 42) → 42 |
%f |
float | printf("%.2f", 3.14159) → 3.14 |
%s |
string | printf("%s", "Java") → Java |
%c |
char | printf("%c", 'A') → A |
%n |
newline (better than ` | |
| `) | portable line break | |
%5d / %-5d |
width 5, right/left align | printf("[%5d]", 7) → [ 7] |
3. Beginner Example — Marksheet Row
String name = "Asha";
int marks = 87;
System.out.printf("%-10s %3d/100%n", name, marks); // Asha 87/100
System.out.printf("%.1f%% passed%n", 92.5); // %% prints %
4. Traps
%fneeds double/float,%dneeds int — mismatch →IllegalFormatConversionException.- Always use
%n(not) inprintffor Windows/Linux safety.
5. Exam Points
- println vs print vs printf — 3-5 marks, frequent.
- Format table + one marksheet program — 5 marks, very frequent.