Creating a Scanner Object: The Basic Steps
To make a Scanner in Java, you import the Scanner class from the java.util package, then create a new Scanner object that reads from System.in (the keyboard). The Scanner class is built into Java and handles input parsing for you—it converts what the user types into the data type you need, whether that's a string, integer, or decimal number.
Here is the simplest way to set up a Scanner:
Step 1: Import the Scanner class at the top of your file
import java.util.Scanner;
Step 2: Create a Scanner object inside your main method or another method
Scanner input = new Scanner(System.in);
That's it. The variable name input is arbitrary—you can call it scan, reader, or anything else. System.in tells Java to read from the keyboard. Once you have created the Scanner, you can call methods on it to read different types of data.
Key Takeaways
- Import java.util.Scanner at the top of your file before you use the Scanner class.
- Create a Scanner object with new Scanner(System.in) to read keyboard input.
- Use nextLine() to read an entire line of text, nextInt() for whole numbers, and nextDouble() for decimal numbers.
- Always close your Scanner with input.close() when you are finished reading input to free up system resources.
- Call hasNextInt() or hasNextLine() before reading to check whether the next input matches the type you expect.
Reading Different Data Types
Once your Scanner is created, you call different methods depending on what kind of input you want to read. The most common methods are nextLine(), nextInt(), nextDouble(), and nextBoolean().
nextLine() reads an entire line of text, including spaces, and stops at the Enter key. Use this when you want to read a person's name or a sentence:
String name = input.nextLine();
nextInt() reads a whole number and skips any whitespace before it. If the user types "42" and presses Enter, nextInt() returns the integer 42:
int age = input.nextInt();
nextDouble() reads a decimal number in the same way:
double price = input.nextDouble();
nextBoolean() reads true or false:
boolean isActive = input.nextBoolean();
A common mistake is mixing nextInt() and nextLine(). When you call nextInt(), it reads the number but leaves the Enter key in the input buffer. If you then call nextLine(), it reads that leftover newline and returns an empty string. To avoid this, call nextLine() after nextInt() to consume the newline:
int age = input.nextInt();input.nextLine(); // consume the newlineString name = input.nextLine();
Checking Input Before Reading
The hasNext methods let you check whether the next piece of input matches the type you expect before you try to read it. This prevents your program from crashing when a user types something unexpected.
hasNextInt() returns true if the next input can be read as an integer:
if (input.hasNextInt()) { int number = input.nextInt();} else { System.out.println("Please enter a whole number.");}
hasNextLine() returns true if there is a line of text to read. hasNextDouble() checks for decimal numbers. Using these methods makes your program more robust because it handles bad input gracefully instead of throwing an exception and stopping.
Closing the Scanner
When you are finished reading input, call the close() method on your Scanner object. This tells Java to release the system resources the Scanner was using:
input.close();
If you do not close the Scanner, Java will eventually close it automatically when your program ends, but it is good practice to close it yourself as soon as you are done. In larger programs, leaving Scanners open can cause resource leaks.
Reading from a File Instead of the Keyboard
You can also create a Scanner that reads from a file instead of the keyboard. This uses the same Scanner class but passes a File object to the constructor:
import java.util.Scanner;import java.io.File;Scanner fileReader = new Scanner(new File("data.txt"));
Once you have created a file Scanner, you read from it the same way—using nextLine(), nextInt(), and the other methods. The difference is that the input comes from the file instead of the user typing. You still need to close the Scanner when you are done:
fileReader.close();
If the file does not exist, Java will throw a FileNotFoundException, so you may need to wrap this in a try-catch block or declare that your method throws the exception.
A Complete Example
Here is a short program that creates a Scanner, reads a name and an age, and prints them back:
import java.util.Scanner;public class InputExample { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter your name: "); String name = input.nextLine(); System.out.print("Enter your age: "); int age = input.nextInt(); System.out.println("Hello, " + name + ". You are " + age + " years old."); input.close(); }}
When you run this program, it prints "Enter your name: " and waits for you to type. After you type your name and press Enter, it prints "Enter your age: " and waits again. Once you type a number and press Enter, it prints a greeting and closes the Scanner.
Frequently Asked Questions
What is the difference between next() and nextLine()?
next() reads a single word (stops at whitespace), while nextLine() reads an entire line including spaces. Use next() if you want individual words and nextLine() if you want a full sentence or phrase.
Why does my program crash when I enter text instead of a number?
When you call nextInt() or nextDouble() and the user types text, Java throws an InputMismatchException. Use hasNextInt() or hasNextDouble() to check the input type before reading, and handle the bad input with an if-else block or a try-catch statement.
Do I have to close the Scanner?
Java closes the Scanner automatically when your program ends, but closing it yourself with close() is considered good practice. It frees up system resources when ready rather than waiting for the program to finish, which matters in long-running applications.
Can I create more than one Scanner in the same program?
Yes. You can create multiple Scanner objects, each reading from a different source—one from the keyboard, one from a file, one from a network connection. Just give each one a different variable name and close each one when you are done.
What does System.in mean?
System.in is Java's standard input stream, which is connected to the keyboard by default. It is part of the System class and represents the source of input for your program. You can redirect it from the command line to read from a file instead, but in most cases it refers to keyboard input.