What the Scanner Class Does and Why You Need It
The Scanner class in Java reads input from the user or from a file and converts it into the data type you need — text, numbers, whole numbers, or decimal values. When you write a program that asks a user to type something, Scanner is the tool that captures what they typed and makes it usable in your code.
Without Scanner, your program has no way to listen to keyboard input. Scanner sits between the user's keyboard and your program's logic, translating raw text into integers, strings, or floating-point numbers that your code can work with.
Key Takeaways
- Import the Scanner class from java.util.Scanner at the top of your file before you use it.
- Create a Scanner object by writing Scanner input = new Scanner(System.in); to read from the keyboard.
- Use nextInt() to read a whole number, nextDouble() for decimals, and nextLine() for text.
- Always close the Scanner when you are done with it by calling input.close(); to free up system resources.
- Check whether input exists before reading it by using hasNextInt(), hasNextDouble(), or hasNextLine().
Importing Scanner and Creating an Instance
Before you can use Scanner, you must import it at the very top of your Java file, above the class declaration. Write this line:
import java.util.Scanner;
Next, create a Scanner object inside your method (usually inside main). The standard way to read from the keyboard is:
Scanner input = new Scanner(System.in);
This line creates a new Scanner object called input that listens to System.in — the keyboard. You can name the object anything you want, but input is a common choice. System.in is always the keyboard input stream in Java.
Reading Different Data Types with Scanner Methods
Scanner has different methods for different types of input. The most common ones are nextInt(), nextDouble(), nextLine(), and next().
nextInt() reads a whole number from the user. If the user types 42, the method returns the integer 42. If the user types text or a decimal, the program crashes with an error. Here is a working example:
System.out.println("Enter your age:");int age = input.nextInt();
nextDouble() reads a decimal number. Use it when you need values like 3.14 or 99.99:
System.out.println("Enter the price:");double price = input.nextDouble();
nextLine() reads an entire line of text, including spaces. Use it when the user types a sentence or a name with multiple words:
System.out.println("Enter your full name:");String name = input.nextLine();
next() reads a single word (stops at the first space). Use it when you only want one word:
System.out.println("Enter a single word:");String word = input.next();
Handling the Newline Problem When Mixing nextInt and nextLine
A common mistake happens when you use nextInt() or nextDouble() followed by nextLine(). When the user presses Enter after typing a number, that newline character stays in the input buffer. The next nextLine() call reads that leftover newline and returns an empty string instead of waiting for the user to type.
To fix this, add an extra nextLine() call right after nextInt() or nextDouble() to consume the leftover newline:
System.out.println("Enter your age:");int age = input.nextInt();input.nextLine(); // consume the newlineSystem.out.println("Enter your name:");String name = input.nextLine();
Now the program works as expected — it reads the age, clears the buffer, and then waits for the name.
Checking for Input Before Reading It
If you try to read an integer with nextInt() but the user types text, your program will crash. To prevent this, use the hasNext methods to check whether valid input is waiting before you read it.
hasNextInt() returns true if the next input is a whole number, hasNextDouble() returns true if it is a decimal, and hasNextLine() returns true if there is a line waiting. Use these in an if statement:
if (input.hasNextInt()) { int number = input.nextInt();} else { System.out.println("That is not a number.");}
This pattern prevents crashes and lets you handle bad input gracefully. You can ask the user to try again or skip the input and move on.
Closing the Scanner When You Are Done
When your program finishes reading input, close the Scanner by calling input.close();. This tells Java to release the system resources that Scanner was using.
Scanner input = new Scanner(System.in);System.out.println("Enter a number:");int num = input.nextInt();System.out.println("You entered: " + num);input.close();
Closing Scanner is not always required for small programs, but it is a good habit. If your program runs for a long time or opens many Scanners, failing to close them can cause resource leaks.
Reading from a File Instead of the Keyboard
Scanner can also read from a file instead of the keyboard. To do this, pass a File object to the Scanner constructor instead of System.in:
import java.io.File;import java.util.Scanner;File myFile = new File("data.txt");Scanner fileScanner = new Scanner(myFile);
Once the Scanner is created, you use the same methods — nextInt(), nextLine(), and so on — to read from the file. The difference is that the input comes from the file instead of the keyboard. Remember to close the file scanner when you are done:
fileScanner.close();
Frequently Asked Questions
What is the difference between next() and nextLine()?
next() reads a single word and stops at the first space or newline. nextLine() reads the entire line, including spaces, and stops only at the newline character. Use next() for single words and nextLine() for sentences or names with spaces.
Why does my program crash when I use nextInt()?
The program crashes because the user typed something that is not a whole number. Use hasNextInt() to check before calling nextInt(). If the check fails, ask the user to enter a valid number or handle the bad input another way.
Do I have to close the Scanner?
Closing Scanner is not required for small programs, but it is a best practice. It frees up system resources. If your program runs for a long time or creates many Scanners, closing them prevents resource leaks.
Can I use Scanner to read from a website or network connection?
Yes, but it requires more setup. You would create a URL connection and pass its input stream to Scanner. For most beginner programs, reading from the keyboard or a local file is more common.
What happens if I call nextInt() when the user types a decimal number?
The program crashes with an exception. Use hasNextInt() to check first, or use nextDouble() if you expect decimal input. If you need to read a decimal and convert it to an integer, read it as a double and cast it to an int.