Creating a Scanner Object: The Basic Syntax

To create a Scanner object in Java, you declare a variable of type Scanner, then instantiate it using the new keyword with an input source. The most common source is System.in, which reads from the keyboard. The line looks like this:

Scanner scanner = new Scanner(System.in);

Before you can use this line, you must import the Scanner class at the top of your file with import java.util.Scanner; — without this import statement, Java will not recognize the Scanner class name and your code will not compile.

Once the Scanner object exists, you can call methods on it to read different types of input: nextLine() for a full line of text, nextInt() for an integer, nextDouble() for a decimal number, and next() for a single word. Each method waits for the user to type and press Enter before the program continues.

Key Takeaways

  • Import the Scanner class with import java.util.Scanner; at the very top of your Java file, before the class declaration.
  • Create a Scanner object with the line Scanner scanner = new Scanner(System.in); inside your method, usually in the main method.
  • Use nextLine() to read an entire line of text, nextInt() for whole numbers, and nextDouble() for decimal numbers.
  • Always close the Scanner when you are done with it by calling scanner.close(); to prevent resource leaks.

Where to Place the Import Statement

The import statement must appear at the top of your Java file, before the class declaration. If your file is named MyProgram.java, the structure looks like this:

import java.util.Scanner; comes first, then a blank line, then public class MyProgram { and the rest of your code. Java reads the file from top to bottom and needs to know about Scanner before it encounters the class that uses it.

If you forget the import, you will see a compiler error that says something like "cannot find symbol — class Scanner". Adding the import line fixes this when ready. Some development environments like Eclipse or IntelliJ can add the import automatically when you type Scanner and press a keyboard shortcut, but understanding where it goes helps you write code in any editor.

Declaring and Instantiating in One Line

The declaration and instantiation happen together in a single statement: Scanner scanner = new Scanner(System.in); This line does two things at once. The left side, Scanner scanner, declares a variable named scanner of type Scanner. The right side, new Scanner(System.in), creates a new Scanner object and connects it to System.in, which is the keyboard input stream.

You can name the variable anything you want — Scanner input = new Scanner(System.in); or Scanner reader = new Scanner(System.in); work just as well. The name you choose is what you will type later when you call methods like input.nextInt() or reader.nextLine(). Pick a name that makes sense in your program so other people reading your code understand what the variable does.

This line typically goes inside a method, most often the main method where your program starts. It does not go at the class level outside of any method, because Scanner needs to be created when the program actually runs, not when the class is loaded.

Reading Input After Creating the Scanner

Once the Scanner object exists, you call methods on it to read what the user types. The method you choose depends on what kind of input you expect. nextLine() reads everything the user types until they press Enter, including spaces. nextInt() reads only the next integer and stops at whitespace. nextDouble() reads a decimal number. next() reads a single word (stops at the first space or newline).

Here is a complete example:

import java.util.Scanner; public class Main { 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(); System.out.println("Hello " + name + ", you are " + age + " years old"); scanner.close(); } }

The program prints a prompt, waits for the user to type and press Enter, stores what they typed in a variable, and moves to the next line. Each method call pauses the program until input arrives.

Closing the Scanner to Avoid Resource Leaks

After you finish reading input, call scanner.close(); to close the Scanner and release the system resources it uses. This is important because every open input stream takes up memory and file handles. If you create many Scanner objects without closing them, your program can run out of resources.

In small practice programs, forgetting to close might not cause a visible problem. In larger applications or programs that run for a long time, unclosed Scanners add up and can slow the system down or cause crashes. Making close() a habit now means your code will work correctly when it matters.

If you are using Java 7 or newer, you can use a try-with-resources statement to close the Scanner automatically without writing close() yourself. The syntax is try (Scanner scanner = new Scanner(System.in)) { followed by your code inside the braces. When the try block ends, Java closes the Scanner for you. This approach is safer because it closes the Scanner even if an error occurs inside the try block.

Creating a Scanner from a File Instead of the Keyboard

You can create a Scanner that reads from a file instead of the keyboard by passing a File object to the Scanner constructor. First, import both Scanner and File: import java.util.Scanner; import java.io.File; Then create the Scanner like this: Scanner scanner = new Scanner(new File("data.txt"));

This opens the file named data.txt in the same folder as your program and creates a Scanner that reads from it line by line. The methods work the same way — nextLine(), nextInt(), and next() all work on file input. You can check if more data exists by calling scanner.hasNextLine() or scanner.hasNextInt() before calling the read method, which prevents errors when you reach the end of the file.

File-based Scanners are useful for reading configuration files, data files, or any text file your program needs to process. The same close() rule applies — call scanner.close(); when you are done to close the file.

Common Mistakes When Creating a Scanner

The most frequent mistake is forgetting the import statement. Without import java.util.Scanner; at the top, the compiler will not recognize Scanner as a class name. The error message will say "cannot find symbol" and point to the line where you wrote Scanner. Adding the import fixes it when ready.

Another common error is trying to use Scanner without the new keyword, like Scanner scanner = System.in; This does not work because System.in is an InputStream, not a Scanner. You must wrap it with new Scanner(System.in) to create the Scanner object.

A third mistake is declaring the Scanner inside a method and then trying to use it outside that method. Variables declared inside a method only exist while that method is running. If you need to use the same Scanner in multiple methods, declare it at the class level (outside all methods) so all methods can access it.

Frequently Asked Questions

Do I have to name the Scanner object "scanner"?

No. You can name it anything you want — input, reader, scan, or any other valid Java variable name. The name you choose is what you type when you call methods on it, so pick something that makes sense in your program.

What happens if I create a Scanner but never close it?

The Scanner stays open and holds onto system resources until the program ends. In small programs this usually does not cause problems, but in larger applications or long-running programs, unclosed Scanners can accumulate and waste memory. Calling close() is a good habit that prevents resource leaks.

Can I create more than one Scanner object in the same program?

Yes, you can create multiple Scanner objects if you need to read from different sources — one from the keyboard, one from a file, one from a network connection. Each Scanner is independent. Just remember to close each one when you are done with it.

What is the difference between nextLine() and next()?

nextLine() reads everything the user types until they press Enter, including spaces. next() reads only the next word and stops at the first space or newline. Use nextLine() for full sentences or lines with spaces, and next() when you expect single words.

Why do I get an error when I try to read an integer with nextInt()?

This usually happens when the user types something that is not a number, or when you call nextInt() and then nextLine() in sequence without handling the leftover newline character. If you need to read an integer and then a full line, call scanner.nextLine(); after nextInt() to consume the newline that nextInt() leaves behind.