Why variables are needed in Java - Performance Analysis
We want to see how using variables affects the steps a program takes.
How does the program's work change when it stores and reuses values?
Analyze the time complexity of the following code snippet.
int sum = 0;
for (int i = 1; i <= n; i++) {
sum += i;
}
System.out.println(sum);
This code adds numbers from 1 to n using a variable to keep the total.
Look at what repeats in the code.
- Primary operation: Adding each number to the sum variable inside the loop.
- How many times: The addition happens once for every number from 1 to n.
As n grows, the program adds more numbers, so it does more work.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The work grows directly with the size of n.
Time Complexity: O(n)
This means the program takes longer in a straight line as n gets bigger.
[X] Wrong: "Using a variable makes the program slower because it adds extra steps."
[OK] Correct: The variable actually helps by storing the total so the program doesn't have to repeat work, keeping the steps simple and clear.
Understanding how variables affect the number of steps helps you explain your code clearly and shows you know how programs work inside.
"What if we removed the variable and printed each number instead? How would the time complexity change?"