What the Scanner class does and when to use it

The Scanner class in Java reads input from the user or from a file, one piece at a time. You create a Scanner object, point it at a source (usually the keyboard), and then call methods to grab the next word, number, or line. It breaks apart what the user types and gives you each part separately, which saves you from writing that parsing code yourself.

Use Scanner when you need a program to wait for the user to type something and then do something with it. A quiz program that reads answers, a calculator that takes two numbers, a login screen — these all use Scanner. If you are reading from a file instead of the keyboard, Scanner works the same way.

Key Takeaways

  • Import java.util.Scanner at the top of your file, then create a Scanner object pointing to 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 it by calling scanner.close() to free up system resources.

Setting up Scanner to read from the keyboard

Start by importing the Scanner class at the very top of your Java file, before the class declaration:

import java.util.Scanner;

Inside your method (usually main), create a new Scanner object and point it to System.in, which represents the keyboard:

Scanner scanner = new Scanner(System.in);

That one line does everything. The variable scanner is now ready to read whatever the user types. You can name the variable anything you want — input, reader, keyboard — but scanner is the most common choice.

Reading different types of input

Scanner has different methods depending on what kind of data you expect. The most common ones are nextLine(), nextInt(), nextDouble(), and next().

nextLine() reads everything the user typed until they press Enter, including spaces. Use this when you want a full sentence or a name:

System.out.println("What is your name?"); String name = scanner.nextLine(); System.out.println("Hello, " + name);

nextInt() reads the next whole number and skips any whitespace before it:

System.out.println("Enter your age:"); int age = scanner.nextInt(); System.out.println("You are " + age + " years old");

nextDouble() works the same way but reads decimal numbers:

System.out.println("Enter a price:"); double price = scanner.nextDouble(); System.out.println("Total: $" + price);

next() reads a single word (stops at whitespace) and is less common than the others:

String word = scanner.next();

Checking for input before you read it

If you call nextInt() and the user types letters instead of numbers, your program will crash. To prevent that, always check whether the next piece of input matches what you expect by using the hasNext methods first.

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 another line to read:

System.out.println("Enter a number:"); if (scanner.hasNextInt()) { int number = scanner.nextInt(); System.out.println("You entered: " + number); } else { System.out.println("That is not a number."); }

This pattern — check first, then read — prevents crashes and lets you handle bad input gracefully. In a real program, you would usually loop and ask the user to try again if the input is wrong.

Mixing nextLine() with nextInt() and nextDouble()

A common mistake happens when you mix nextInt() or nextDouble() with nextLine(). When you call nextInt(), it reads the number but leaves the Enter key press in the input buffer. The next call to nextLine() reads that leftover newline and returns an empty string.

Here is the problem:

System.out.println("Enter your age:"); int age = scanner.nextInt(); System.out.println("Enter your name:"); String name = scanner.nextLine(); // This will be empty

To fix it, call scanner.nextLine() 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

A safer approach is to read everything as a line first, then parse it into the type you need — but for straightforward programs, the extra nextLine() call is the quickest fix.

Closing the Scanner when you are done

When your program finishes reading input, close the Scanner to release the system resources it was using:

scanner.close();

Put this at the end of your program or in a finally block if you are using exception handling. For small practice programs, forgetting to close is not a big problem, but in real applications it matters — an unclosed Scanner can prevent other parts of your program from reading input later.

Reading from a file instead of the keyboard

Scanner can read from a file just as easily as from the keyboard. Instead of System.in, pass a File object to the Scanner constructor:

import java.util.Scanner; import java.io.File; Scanner scanner = new Scanner(new File("data.txt")); while (scanner.hasNextLine()) { String line = scanner.nextLine(); System.out.println(line); }

The methods work exactly the same — nextLine(), nextInt(), and the rest all behave identically. The only difference is where the input comes from. If the file does not exist, this will throw an exception, so wrap it in a try-catch block in production code.

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 everything up to and including the newline, so it captures entire lines with spaces. Use nextLine() for sentences or names, and next() only when you know the input is a single word.

Why does my program crash when I use nextInt()?

You are probably entering text instead of a number. Always use hasNextInt() before calling nextInt() to check that the input is actually a number. If it is not, handle the error case instead of crashing.

Do I have to close the Scanner?

Technically no for small programs, but yes for real ones. Closing the Scanner frees up system resources and prevents resource leaks. It is good practice to always call scanner.close() when you are done, especially if your program runs for a long time or opens many Scanners.

Can Scanner read from the internet or a database?

Scanner can read from any input stream, including network connections and database result sets. You would pass the stream to the Scanner constructor instead of System.in or a File object. The reading methods work the same way.