What Java Scanner Does and How to Set It Up

Java Scanner is a built-in class that reads text from a source — usually the keyboard, a file, or a string — and breaks it into smaller pieces you can work with. When you create a Scanner object, you point it at a source, and then you call methods on that object to pull out the next word, number, or line.

To use Scanner, you first import it at the top of your Java file:

import java.util.Scanner;

Then you create a Scanner object. The most common way is to read from the keyboard (called standard input):

Scanner scanner = new Scanner(System.in);

Once the Scanner exists, you can call methods on it to read different types of input. The Scanner will wait for the user to type something and press Enter, then hand you back what they typed in the format you asked for.

Key Takeaways

  • Create a Scanner by writing new Scanner(System.in) to read from the keyboard, or new Scanner(new File("filename.txt")) to read from a file.
  • Use nextLine() to read an entire line of text, nextInt() to read a whole number, and nextDouble() to read a decimal number.
  • Always close the Scanner when you are done by calling scanner.close() to free up system resources.
  • Check whether input is available before reading it by using hasNextInt(), hasNextDouble(), or hasNextLine() to avoid crashes.
  • When mixing nextLine() with nextInt() or nextDouble(), call nextLine() after the number methods to clear the leftover newline character.

Reading Different Types of Input

Scanner has different methods depending on what kind of data you want to read. The most common ones are:

nextLine() reads everything the user types until they press Enter, including spaces. It returns a String. nextInt() reads the next whole number and skips any whitespace before it. nextDouble() reads the next decimal number. next() reads the next single word (stops at whitespace).

Here is a straightforward example that reads a name and an age:

Scanner scanner = new Scanner(System.in); System.out.print("Enter your name: "); String name = scanner.nextLine(); System.out.print("Enter your age: "); int age = scanner.nextInt(); System.out.println("Hello " + name + ", you are " + age + " years old"); scanner.close();

When you run this, the program prints the first prompt, waits for input, reads the name, prints the second prompt, waits again, reads the age, and then prints the result.

Reading from Files Instead of the Keyboard

Scanner can read from a file on your computer instead of waiting for keyboard input. To do this, you pass a File object to the Scanner constructor:

import java.io.File; import java.util.Scanner; Scanner scanner = new Scanner(new File("data.txt"));

You need to import java.io.File as well as Scanner. After that, you use the same methods — nextLine(), nextInt(), and so on — to read from the file instead of the keyboard.

One difference: when reading from a file, you often want to read multiple lines or records. Use a loop with hasNextLine() to check whether there is more to read:

while (scanner.hasNextLine()) {   String line = scanner.nextLine();   System.out.println(line); }

This loop keeps reading lines until the file ends. Always close the Scanner when you are done, even when reading from a file.

Checking Before You Read to Avoid Crashes

If you call nextInt() but the user types a word instead of a number, your program will crash with an exception. To prevent this, use the hasNext methods to check whether the next piece of input is the type you expect:

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

The hasNext methods return true or false. hasNextInt() checks for a whole number, hasNextDouble() checks for a decimal, hasNextLine() checks whether there is another line to read, and hasNext() checks whether there is any word at all.

This pattern is especially important when reading from files, because you cannot ask the user to fix their input — you need to handle bad data gracefully.

The Newline Problem When Mixing Input Methods

A common mistake happens when you use nextInt() or nextDouble() followed by nextLine(). The number methods read the number but leave the newline character (the Enter key press) sitting in the input stream. When you then call nextLine(), it reads that leftover newline and returns an empty string.

Here is the problem:

System.out.print("Enter a number: "); int number = scanner.nextInt(); // reads 5, leaves the newline System.out.print("Enter text: "); String text = scanner.nextLine(); // reads the empty newline, not your text

The fix is to call nextLine() right after the number method to consume that leftover newline:

System.out.print("Enter a number: "); int number = scanner.nextInt(); scanner.nextLine(); // consume the newline System.out.print("Enter text: "); String text = scanner.nextLine(); // now reads your actual text

This is a small detail but it trips up many people, so remember to add that extra nextLine() call whenever you mix number input with text input.

Closing the Scanner and Freeing Resources

When you are done reading, always call scanner.close(). This tells Java to release the resources the Scanner was using — the connection to the keyboard, file, or other source.

scanner.close();

If you do not close the Scanner, Java will eventually close it for you when the program ends, but it is good practice to close it yourself as soon as you are done. If you are reading from a file and you forget to close the Scanner, the file may stay locked and you might not be able to edit or delete it until the program exits.

In larger programs, you can use a try-with-resources statement to close the Scanner automatically:

try (Scanner scanner = new Scanner(System.in)) {   // use the scanner here } // scanner closes automatically

This syntax ensures the Scanner is closed even if an error occurs, so you do not have to remember to call close() yourself.

Common Scanner Methods at a Glance

MethodWhat It DoesReturns
nextLine()Reads everything until the next Enter key pressString
nextInt()Reads the next whole numberint
nextDouble()Reads the next decimal numberdouble
next()Reads the next single word (stops at whitespace)String
hasNextLine()Checks whether another line existsboolean
hasNextInt()Checks whether the next input is a whole numberboolean
hasNextDouble()Checks whether the next input is a decimal numberboolean
close()Closes the Scanner and frees resourcesvoid

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 in them. Use nextLine() when you want the user to type a full sentence or phrase.

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

This usually happens because the user typed something that is not a number, or because you did not check with hasNextInt() first. Always use the hasNext methods to verify the input type before calling the read method, or wrap the read in a try-catch block to handle the error.

Can I use Scanner to read from a string instead of a file or keyboard?

Yes. Pass a String to the Scanner constructor: Scanner scanner = new Scanner("hello world 123"); Then use the same methods to read words and numbers from that string. This is useful for testing or parsing data that is already in memory.

Do I have to close the Scanner if I am reading from the keyboard?

Technically no — Java will close it when the program ends. But it is good practice to close it anyway, especially if your program runs for a long time or creates many Scanners. Closing it frees up system resources and prevents potential issues.

What happens if I try to read past the end of a file?

If you call nextLine() when there are no more lines, Scanner throws a NoSuchElementException. This is why you should always use hasNextLine() in a loop before calling nextLine() — it prevents the crash by checking whether input is available first.