Writing first Java program - Time & Space 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.
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 the loops, recursion, array traversals that repeat.
- Primary operation: Printing one message to the screen.
- How many times: Exactly once.
Since the program prints only one message, the time it takes does not change with input size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 |
| 100 | 1 |
| 1000 | 1 |
Pattern observation: The number of steps stays the same no matter how big the input is.
Time Complexity: O(1)
This means the program takes the same amount of time no matter how big the input is.
[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.
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.
"What if we added a loop to print the message multiple times? How would the time complexity change?"