What the Scanner Class Does and When to Use It
The Scanner class in Java reads input from the user (or from a file or string) and breaks it into separate pieces you can work with. When you create a Scanner object pointing to System.in, it listens to what the user types and lets you grab individual words, numbers, or whole lines without writing the parsing code yourself.
You use Scanner when your program needs to respond to what someone types—a quiz that asks for answers, a calculator that waits for numbers, a login screen that reads a username. Without Scanner, you would have to manually convert the raw text into the data type you actually need, which is tedious and error-prone.
Key Takeaways
- Import java.util.Scanner at the top of your file, then create a Scanner object with new Scanner(System.in) to read from the keyboard.
- Use nextLine() to read an entire line of text, nextInt() for whole numbers, and nextDouble() for decimals.
- Always check whether input exists before reading it by calling hasNextInt(), hasNextDouble(), or hasNextLine() first.
- Close the Scanner when you are done with scanner.close() to free up system resources.
- A common mistake is mixing nextLine() with nextInt() or nextDouble(), which leaves a newline character behind and skips your next input.
Setting Up Scanner: Import and Initialization
Start by importing the Scanner class at the very top of your Java file, before the class declaration:
import java.util.Scanner;
Inside your main method (or any method where you need input), create a Scanner object that points to System.in, which is the keyboard:
Scanner scanner = new Scanner(System.in);
From this point forward, you can call methods on the scanner object to read what the user types. The Scanner waits for input and does not move forward until the user presses Enter.
Reading Different Types of Input
Scanner offers different methods depending on what kind of data you expect. The most common ones are:
- nextLine() — reads an entire line of text, including spaces, and stops at the newline character.
- nextInt() — reads the next whole number and skips any whitespace before it.
- nextDouble() — reads the next decimal number.
- next() — reads the next single word (stops at whitespace).
Here is a straightforward example that reads a name and an age:
System.out.println("Enter your name:"); String name = scanner.nextLine(); System.out.println("Enter your age:"); int age = scanner.nextInt();
When the user types "Alice" and presses Enter, nextLine() stores "Alice" in the name variable. When they type "25" and press Enter, nextInt() stores 25 in the age variable as an integer, not a string.
Checking for Input Before Reading It
A program that crashes because the user entered the wrong type of data looks broken. Before you call nextInt(), nextDouble(), or nextLine(), check whether that type of input is actually waiting to be read:
- hasNextInt() — returns true if the next input is a whole number.
- hasNextDouble() — returns true if the next input is a decimal number.
- hasNextLine() — returns true if there is a line of text waiting.
- hasNext() — returns true if there is any word waiting.
Wrap your input call in an if statement:
if (scanner.hasNextInt()) { int number = scanner.nextInt(); System.out.println("You entered: " + number); } else { System.out.println("That is not a number. Try again."); }
This pattern prevents your program from crashing when a user types "abc" instead of a number. The hasNextInt() check returns false, and your program handles it gracefully.
The Newline Problem: Mixing nextLine() with nextInt()
One of the most common mistakes happens when you use nextInt() or nextDouble() followed by nextLine(). After nextInt() reads "25", it leaves the newline character (the Enter key press) sitting in the input buffer. When you call nextLine() next, it reads that leftover newline and returns an empty string instead of waiting for the user to type something new.
Here is the problem in action:
System.out.println("Enter your age:"); int age = scanner.nextInt(); // User types 25 and presses Enter System.out.println("Enter your name:"); String name = scanner.nextLine(); // This reads the leftover newline and returns ""
The fix is to call scanner.nextLine() right after nextInt() to consume that leftover newline:
System.out.println("Enter your age:"); int age = scanner.nextInt(); scanner.nextLine(); // Consume the newline System.out.println("Enter your name:"); String name = scanner.nextLine(); // Now this works correctly
Closing the Scanner When You Are Done
When your program finishes reading input, close the Scanner to release the system resources it is using:
scanner.close();
In a short program that runs once and exits, this is not critical. In a long-running process or a program that creates many Scanner objects, closing them prevents resource leaks. A common pattern is to close the Scanner at the end of your main method or in a finally block if you are handling exceptions.
Frequently Asked Questions
What is the difference between next() and nextLine()?
next() reads only the next word (it stops at any whitespace like spaces or tabs), while nextLine() reads the entire line including spaces. If the user types "Hello World", next() returns "Hello" and leaves "World" in the buffer, but nextLine() returns "Hello World".
Can I use Scanner to read from a file instead of the keyboard?
Yes. Instead of new Scanner(System.in), you can write new Scanner(new File("filename.txt")) to read from a file. You will need to import java.io.File and handle the checked exception that file reading can throw.
What happens if the user enters a decimal number when I call nextInt()?
Scanner will throw an exception and your program will crash unless you catch it. This is why checking with hasNextInt() first is important—it returns false if the next input is a decimal, so you can handle it before calling nextInt().
Do I have to close Scanner if my program is about to end anyway?
Technically no—the operating system will clean up when the program exits. In practice, closing it is good habit and makes your code cleaner. If you are writing code that will be part of a larger system, closing resources you open is expected.
Can Scanner read from a string instead of user input?
Yes. You can create a Scanner from a string with new Scanner("some text here") and use the same methods to parse it. This is useful for testing or processing strings that are already in your program.