Output using System.out.print in Java - Time & Space Complexity
Let's see how the time it takes to print output grows when using System.out.print in Java.
We want to know how printing many items affects the program's speed.
Analyze the time complexity of the following code snippet.
for (int i = 0; i < n; i++) {
System.out.print(i + " ");
}
This code prints numbers from 0 up to n-1 on the same line.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The loop runs and prints one number each time.
- How many times: It repeats exactly n times, once for each number.
As n grows, the number of print operations grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 prints |
| 100 | 100 prints |
| 1000 | 1000 prints |
Pattern observation: The work grows directly with n; doubling n doubles the prints.
Time Complexity: O(n)
This means the time to print grows in a straight line as the number of items increases.
[X] Wrong: "Printing output is instant and does not affect time complexity."
[OK] Correct: Each print takes time, so printing many times adds up and grows with the number of prints.
Understanding how output operations scale helps you reason about program speed and efficiency in real tasks.
"What if we used System.out.println instead of System.out.print inside the loop? How would the time complexity change?"