The java scanner object is a class from the java.util package that reads input from a stream such as System.in (keyboard input) or a file. It parses primitive data types and strings using delimiters like whitespace or newlines.
When you create a Scanner object, you pass a source-typically System.in-to its constructor. The object then buffers input until you call a parsing method like nextInt(), nextDouble(), or nextLine(). These methods read and convert the next token from the input stream based on the expected type.
For example, if a user types "42" followed by Enter, calling scanner.nextInt() returns the integer 42. If they type "Hello world", calling scanner.nextLine() returns the string "Hello world". This behavior makes the Scanner object essential for interactive programs that require user input.
The Scanner class uses a regular expression delimiter pattern by default. This pattern splits input into tokens based on whitespace-spaces, tabs, and newlines. When you call a method like next(), it consumes the next token and moves the internal pointer forward.
Each Scanner object maintains an internal buffer of input. As long as input remains available, you can keep calling parsing methods. Once the input stream ends, calling next() throws a NoSuchElementException.
After reading input, always close the Scanner object with close() to free system resources. Failing to do so may cause resource leaks, especially in loops or long-running applications.
A java scanner object consists of three core components: the input source, the delimiter pattern, and the internal state. The input source is typically a Reader or InputStream. For keyboard input, this is System.in.
The delimiter pattern controls how input is split into tokens. By default, it's \s+ (one or more whitespace characters). You can change it using useDelimiter(Regex). For example, useDelimiter(",") lets you parse comma-separated values.
The internal state tracks the current position in the input stream. Methods like hasNextInt() check whether the next token can be parsed as an integer without consuming it. This allows safe validation before reading.
| Method | Purpose | Example Input | Returns |
|---|---|---|---|
| nextInt() | Reads next integer | "123" | 123 (int) |
| nextLine() | Reads entire line | "Hello, world" | "Hello, world" (String) |
| hasNextDouble() | Checks if next token is double | "3.14" | true (boolean) |
| useDelimiter(";") | Changes token separator | "red;blue;green" | Tokenized by semicolons |
Developers use the java scanner object in command-line applications, quizzes, configuration readers, and testing scripts. It's ideal for programs that need to accept changing input during execution.
For example, a grade calculator program might prompt users to enter student scores. Using Scanner, the program reads each score via nextDouble(), accumulates them, and computes an average. Without Scanner, manually parsing strings would be error-prone and repetitive.
Another common use is reading configuration files. A program might load settings from a text file where each line contains a key-value pair separated by a colon. By setting the delimiter to ":", Scanner can extract both parts cleanly.
Many beginners assume that nextLine() reads the entire input stream. It does not. It only reads up to the next newline character. If you call nextLine() immediately after nextInt(), the method may return an empty string because the newline left by the previous input hasn't been consumed.
This is a frequent bug. After calling nextInt(), you must call nextLine() once to consume the leftover newline. Otherwise, the next nextLine() call returns an empty string. This happens because nextInt() stops at the number but leaves the newline in the buffer.
For example:
Scanner sc = new Scanner(System.in);
System.out.print("Enter age: ");
int age = sc.nextInt(); // Input: "25\n"
sc.nextLine(); // Consume the newline
System.out.print("Enter name: ");
String name = sc.nextLine(); // Now reads "Alice"
Without the extra sc.nextLine(), the name field would be blank. This issue is often missed in tutorials but appears in real-world debugging.
I once built a CLI tool to calculate compound interest. The program asked for principal, rate, and time. I used Scanner to read each value. After fixing the newline bug, the tool worked reliably across multiple test runs. Without proper buffer management, it failed silently on the second input.
The java scanner object is not a replacement for BufferedReader or FileReader. It's designed for parsing structured input, not raw byte streams. For high-performance file reading or network data, use lower-level classes.
Also, it's not thread-safe. Creating a single Scanner object and sharing it across threads causes unpredictable results. If you need concurrent input processing, use separate instances per thread or switch to a streaming parser.
Finally, don't confuse Scanner with System.console(). The console() method provides a secure way to read passwords without echoing. Scanner doesn't handle password masking. Use Console.readPassword() for sensitive input.
Always close your Scanner object. Wrap it in a try-with-resources block to ensure cleanup:
try (Scanner sc = new Scanner(System.in)) {
System.out.print("Enter a number: ");
int num = sc.nextInt();
System.out.println("You entered: " + num);
} // Automatically closes sc
Use specific parsing methods like nextInt() instead of relying on next() and manual conversion. This reduces errors and improves readability.
Validate input before processing. Use hasNextInt() to check if the next token is valid before calling nextInt(). This prevents InputMismatchException crashes.
For complex input formats, consider using a dedicated parser library like Jackson or Gson. Scanner works well for simple cases but becomes unwieldy with nested structures.
Understanding the java scanner object is foundational for building interactive Java applications. It handles input parsing efficiently and integrates smoothly with standard libraries.