The Scanner class reads input from the keyboard and converts it into the data type you need
The Scanner class in Java lets you capture what a user types and turn it into usable data — text, numbers, whole lines. You create a Scanner object, point it at the input source (usually the keyboard), and call methods like nextInt() or nextLine() to pull in and parse the data. It handles the conversion automatically, so you do not have to manually parse strings yourself.
Scanner lives in the java.util package, so you must import it before you use it. Once imported and instantiated, it becomes the standard way to handle keyboard input in command-line Java programs.
Key Takeaways
- Import Scanner from java.util and create an instance pointing to System.in to read from the keyboard.
- Use nextInt() for whole numbers, nextDouble() for decimals, next() for single words, and nextLine() for entire lines of text.
- Always call close() on your Scanner when you are done to release the resource and avoid memory leaks.
- The hasNext() family of methods lets you check whether input is available before you try to read it, preventing crashes on empty input.
Import Scanner and create an instance
At the top of your Java file, add the import statement:
import java.util.Scanner;
Inside your main method or wherever you need to read input, create a Scanner object and point it to System.in, which represents the keyboard:
Scanner scanner = new Scanner(System.in);
This single line does two things: it imports the class and creates an object ready to read. From this point forward, you call methods on scanner to pull in user input.
Read different data types with the right method
Scanner provides several methods, each designed for a specific data type. nextInt() reads a whole number and returns an int. nextDouble() reads a decimal number and returns a double. next() reads a single word (everything up to the next space or newline) and returns a String. nextLine() reads an entire line, including spaces, and returns a String.
Here is a practical example:
System.out.println("Enter your age:"); int age = scanner.nextInt(); System.out.println("Enter your name:"); String name = scanner.nextLine();
The first call reads an integer. The second reads a full line of text. Choose the method that matches what you expect the user to enter.
Handle the newline character when mixing nextInt() and nextLine()
A common pitfall: when you call nextInt(), it reads the number but leaves the newline character in the input buffer. If you then call nextLine(), it reads that leftover newline and returns an empty string instead of waiting for the user to type.
To fix this, call an extra nextLine() right after nextInt() to consume the newline:
int age = scanner.nextInt(); scanner.nextLine(); // consume the newline String name = scanner.nextLine(); // now this waits for input
This pattern prevents your program from skipping over text input that comes after a numeric input.
Check for input before you read it
The hasNext() family of methods lets you test whether input is available before you try to read it. hasNextInt() returns true if the next token can be parsed as an integer. hasNextDouble() checks for a decimal number. hasNextLine() checks whether a line is available.
Use these to prevent crashes when input is missing or malformed:
if (scanner.hasNextInt()) { int number = scanner.nextInt(); } else { System.out.println("That is not a valid number."); }
This pattern is especially useful in loops where you read multiple inputs and want to handle bad data gracefully.
Close the Scanner when you are done
Always call close() on your Scanner object before your program ends:
scanner.close();
This releases the system resource (the input stream) and prevents memory leaks. In small programs it may not matter, but in larger applications or long-running processes, failing to close resources can cause problems.
If you are using Java 7 or later, you can use a try-with-resources statement to close the Scanner automatically:
try (Scanner scanner = new Scanner(System.in)) { // your code here } // scanner closes automatically
A complete example: reading multiple inputs
Here is a short program that reads a name, age, and salary, then prints them back:
import java.util.Scanner; public class InputExample { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Enter your name:"); String name = scanner.nextLine(); System.out.println("Enter your age:"); int age = scanner.nextInt(); scanner.nextLine(); // consume newline System.out.println("Enter your salary:"); double salary = scanner.nextDouble(); System.out.println("Name: " + name + ", Age: " + age + ", Salary: " + salary); scanner.close(); } }
This program creates a Scanner, reads three different data types, prints them, and closes the Scanner. It demonstrates the most common use cases in a single flow.
Frequently Asked Questions
What is the difference between next() and nextLine()?
next() reads a single word — it stops at the first space or newline. nextLine() reads an entire line, including spaces, and stops only at the newline character. Use next() for individual words and nextLine() for full sentences or lines with spaces.
Why does my program skip input when I mix nextInt() and nextLine()?
nextInt() leaves the newline character in the input buffer. When you call nextLine() when ready after, it reads that leftover newline and returns an empty string. Call an extra scanner.nextLine() right after nextInt() to consume the newline before reading text.
Can I read from a file instead of the keyboard?
Yes. Instead of new Scanner(System.in), use new Scanner(new File("filename.txt")). You will need to import java.io.File and handle the FileNotFoundException that may be thrown if the file does not exist.
What happens if the user enters the wrong data type?
If you call nextInt() and the user types text, Scanner throws an InputMismatchException. Use hasNextInt() to check before reading, or wrap your input in a try-catch block to handle the exception gracefully.
Do I have to close the Scanner?
Yes, you should. Closing releases the system resource. For small programs it may not cause visible problems, but it is good practice. Use try-with-resources to close automatically, or call scanner.close() at the end of your program.