Reading string input in Java - Time & Space Complexity
When we read a string input in Java, we want to know how the time it takes changes as the input gets bigger.
We ask: How does reading a longer string affect the time the program runs?
Analyze the time complexity of the following code snippet.
import java.util.Scanner;
public class InputExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
System.out.println("You entered: " + input);
scanner.close();
}
}
This code reads a full line of text from the user and then prints it back.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Reading each character of the input line one by one internally.
- How many times: Once for each character in the input string.
As the input string gets longer, the time to read it grows in a straight line.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 character reads |
| 100 | About 100 character reads |
| 1000 | About 1000 character reads |
Pattern observation: The time grows directly with the number of characters; double the input, double the work.
Time Complexity: O(n)
This means the time to read the input grows linearly with the length of the string.
[X] Wrong: "Reading input always takes the same time no matter how long it is."
[OK] Correct: Actually, the program reads each character one by one, so longer input means more work and more time.
Understanding how input reading scales helps you write programs that handle big data smoothly and shows you think about efficiency.
"What if we read input character by character instead of line by line? How would the time complexity change?"