Reading — step 1 of 5
Learn
Formatting
Building output by gluing strings with + works, but it gets noisy fast and gives you no control over decimals, padding, or alignment. Java's answer is a pair of near-twin tools, both using C-style format specifiers:
String s = String.format("%s is %d years old", "Alice", 30); // returns the String
System.out.printf("%s is %d years old%n", "Alice", 30); // prints it directly
Same mini-language, different destination: String.format hands you the result to store or pass around; System.out.printf writes straight to stdout. Learn one and you've learned both.
The specifier mini-language
A format specifier starts with % and says "a value goes here, formatted like this":
| Specifier | Meaning |
|---|---|
%s | string (any object — uses its toString) |
%d | decimal integer |
%f | floating point — defaults to 6 decimals |
%.2f | floating point, exactly 2 decimals |
%5d | integer right-aligned in 5 columns |
%-10s | string left-aligned in 10 columns |
%n | newline |
Width and precision compose: %8.2f means "8 columns wide, 2 decimal places" — the backbone of every aligned table you'll ever print.
System.out.printf("%-8s | %6.2f%n", "total", 12.5);
// total | 12.50
The traps
Type mismatches blow up at runtime, not compile time. The format string is just text — the compiler doesn't look inside it:
System.out.printf("%d%n", "Alice"); // compiles fine...
// runtime: IllegalFormatConversionException: d != java.lang.String
printf does not add a newline. println always appends one; printf prints exactly what the format string says — nothing more. If your format string doesn't end with %n (or \n), the line is left unterminated, and an exact-match grader will notice the missing newline:
System.out.printf("done"); // no newline — output line never ends
System.out.printf("done%n"); // complete line
Which to use when
- One value, no special formatting →
printlnwith simple+concatenation is fine. - Decimals, alignment, or several values woven into a sentence →
printf/String.format. - Need the string for later (store it, return it) →
String.format.
Java 15+ also has text blocks (""" triple-quoted multi-line strings) for big literals — good to recognize in modern code, rarely needed for line-based output like these exercises.
Your exercise
Read a name and an age (the starter parses them for you), then print exactly:
Hi, {name}! You are {age} years old.
Two equally correct paths:
System.out.printf("Hi, %s! You are %d years old.%n", name, age);
// or
System.out.println("Hi, " + name + "! You are " + age + " years old.");
For Alice / 25 the grader expects Hi, Alice! You are 25 years old. — character for character. The mistakes it will catch: dropping the comma after Hi, the ! after the name, or the final period — and, if you use printf, forgetting the %n at the end, which leaves the line without its closing newline.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…