Command line execution in Java - Time & Space Complexity
When running a Java program from the command line, it's helpful to know how the program's running time changes as the input grows.
We want to see how the program's steps increase when we give it more data.
Analyze the time complexity of the following code snippet.
public class SumArray {
public static void main(String[] args) {
int n = Integer.parseInt(args[0]);
int sum = 0;
for (int i = 0; i < n; i++) {
sum += i;
}
System.out.println(sum);
}
}
This program reads a number from the command line, sums all numbers from 0 up to that number minus one, and prints the result.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that adds numbers from 0 to n-1.
- How many times: The loop runs exactly n times, once for each number.
As the input number n grows, the number of additions grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: If you double n, the work roughly doubles too.
Time Complexity: O(n)
This means the program's running time grows in a straight line with the input size.
[X] Wrong: "The program runs instantly no matter the input size because it just sums numbers."
[OK] Correct: Even simple addition repeated many times takes more time as the input grows, so the program takes longer with bigger numbers.
Understanding how command line input affects program speed helps you explain your code clearly and shows you know how programs behave with different data sizes.
"What if we changed the loop to run from 0 to n squared? How would the time complexity change?"