Primitive to object conversion in Java - Time & Space Complexity
When converting primitive values to objects in Java, it's important to understand how the time needed changes as we handle more data.
We want to know how the cost grows when converting many primitives to objects.
Analyze the time complexity of the following code snippet.
int[] numbers = {1, 2, 3, 4, 5};
Integer[] objects = new Integer[numbers.length];
for (int i = 0; i < numbers.length; i++) {
objects[i] = Integer.valueOf(numbers[i]);
}
This code converts each primitive int in an array to an Integer object and stores it in a new array.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through the array and converting each int to Integer.
- How many times: Once for each element in the input array.
Each element requires one conversion operation, so the total work grows directly with the number of elements.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 conversions |
| 100 | 100 conversions |
| 1000 | 1000 conversions |
Pattern observation: The work increases evenly as the input size grows.
Time Complexity: O(n)
This means the time needed grows in direct proportion to the number of primitives converted.
[X] Wrong: "Converting primitives to objects happens instantly and does not depend on input size."
[OK] Correct: Each conversion takes time, so doing many conversions adds up and grows with the number of elements.
Understanding how simple conversions scale helps you reason about performance in real programs, showing you can think about efficiency clearly.
"What if we used a stream to convert the primitives to objects instead of a loop? How would the time complexity change?"
