0
0
Javaprogramming~5 mins

Writing first Java program - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Writing first Java program
O(1)
Understanding Time Complexity

When writing your first Java program, it's helpful to know how the program's steps grow as you add more instructions or data.

We want to see how the time to run changes when the program gets bigger.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, world!");
    }
}

This program prints a simple greeting message once.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Printing one message to the screen.
  • How many times: Exactly once.
How Execution Grows With Input

Since the program prints only one message, the time it takes does not change with input size.

Input Size (n)Approx. Operations
101
1001
10001

Pattern observation: The number of steps stays the same no matter how big the input is.

Final Time Complexity

Time Complexity: O(1)

This means the program takes the same amount of time no matter how big the input is.

Common Mistake

[X] Wrong: "The program takes longer if I run it on a bigger computer or with more data."

[OK] Correct: This program always does just one print, so its time does not depend on input size.

Interview Connect

Understanding that some programs run in constant time helps you explain how simple tasks behave, which is a great foundation for learning more complex code.

Self-Check

"What if we added a loop to print the message multiple times? How would the time complexity change?"