Java platform and JVM overview - Time & Space Complexity
We want to understand how the Java platform and JVM handle running code as the program size grows.
How does the time to run Java code change when the program or input gets bigger?
Analyze the time complexity of the following Java code snippet.
public class SumArray {
public static int sum(int[] numbers) {
int total = 0;
for (int num : numbers) {
total += num;
}
return total;
}
}
This code sums all numbers in an array using a simple loop.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each element in the array.
- How many times: Once for every element in the input array.
As the array gets bigger, the loop runs more times, so the work grows steadily.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The number of operations grows directly with the input size.
Time Complexity: O(n)
This means the time to run the code grows in a straight line as the input size grows.
[X] Wrong: "The JVM makes the code run instantly no matter how big the input is."
[OK] Correct: The JVM helps run code efficiently, but the time still depends on how many steps the code needs to do.
Understanding how Java code runs and grows with input size helps you explain your code's efficiency clearly and confidently.
"What if we changed the loop to a nested loop over the array? How would the time complexity change?"