Output formatting basics in Java - Time & Space Complexity
We want to see how the time to format output grows as the program runs.
How does the program's work change when formatting more data?
Analyze the time complexity of the following code snippet.
for (int i = 0; i < n; i++) {
System.out.printf("Item %d: %.2f\n", i, Math.random());
}
This code prints n lines, each with a formatted number and index.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that runs n times.
- How many times: Exactly once per item, so n times.
Each new item adds one more formatted print line, so work grows steadily.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 formatted print lines |
| 100 | 100 formatted print lines |
| 1000 | 1000 formatted print lines |
Pattern observation: The work grows directly with the number of items.
Time Complexity: O(n)
This means the time to format output grows in a straight line as the input size grows.
[X] Wrong: "Formatting output is instant and does not affect time."
[OK] Correct: Each formatted print takes time, so more lines mean more work.
Understanding how output formatting scales helps you write efficient programs and explain your code clearly.
"What if we formatted and printed two values per loop instead of one? How would the time complexity change?"