Type casting in Java - Time & Space Complexity
Let's see how time changes when we convert one data type to another in Java.
We want to know how the work grows when casting values.
Analyze the time complexity of the following code snippet.
int[] numbers = {10, 20, 30, 40, 50};
for (int i = 0; i < numbers.length; i++) {
double value = numbers[i];
System.out.println(value);
}
This code converts each integer in an array to a double and prints it.
Look for loops or repeated steps.
- Primary operation: Casting each integer to double inside the loop.
- How many times: Once for each element in the array.
As the array gets bigger, the number of casts grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 casts |
| 100 | 100 casts |
| 1000 | 1000 casts |
Pattern observation: The work grows directly with the number of items.
Time Complexity: O(n)
This means the time to cast grows in a straight line with the number of elements.
[X] Wrong: "Casting is instant and does not add any time."
[OK] Correct: Even simple casts happen for each item, so more items mean more work.
Understanding how casting affects time helps you explain code efficiency clearly and confidently.
"What if we casted inside a nested loop over the same array? How would the time complexity change?"