Default values in Java - Time & Space Complexity
We want to see how the time it takes to run code changes when using default values in Java.
Specifically, we ask: does setting default values affect how long the program runs as input grows?
Analyze the time complexity of the following code snippet.
public class DefaultValues {
public static void fillArray(int[] arr) {
for (int i = 0; i < arr.length; i++) {
arr[i] = 0; // default value
}
}
}
This code fills an array with the default value 0 by looping through each element.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that sets each array element to 0.
- How many times: It runs once for each element in the array, so as many times as the array length.
As the array gets bigger, the number of steps grows in a straight line.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 steps |
| 100 | 100 steps |
| 1000 | 1000 steps |
Pattern observation: If you double the array size, the work doubles too.
Time Complexity: O(n)
This means the time to fill the array grows directly with the number of elements.
[X] Wrong: "Setting default values is instant and does not depend on array size."
[OK] Correct: Each element must be set one by one, so the time grows with the array length.
Understanding how loops over arrays affect time helps you explain code efficiency clearly and confidently.
"What if we used a built-in method like Arrays.fill instead of a loop? How would the time complexity change?"