0
0
Javaprogramming~5 mins

Why variables are needed in Java - Performance Analysis

Choose your learning style9 modes available
Time Complexity: Why variables are needed
O(n)
Understanding Time Complexity

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?

Scenario Under Consideration

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.

Identify Repeating Operations

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.
How Execution Grows With Input

As n grows, the program adds more numbers, so it does more work.

Input Size (n)Approx. Operations
1010 additions
100100 additions
10001000 additions

Pattern observation: The work grows directly with the size of n.

Final Time Complexity

Time Complexity: O(n)

This means the program takes longer in a straight line as n gets bigger.

Common Mistake

[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.

Interview Connect

Understanding how variables affect the number of steps helps you explain your code clearly and shows you know how programs work inside.

Self-Check

"What if we removed the variable and printed each number instead? How would the time complexity change?"