Everything You Need to Know About Java Scanner

Even though Java Scanner was introduced long time ago in the Java SE 5 version in 2004, developers still ask questions about its use and particular use cases. In this article, we answer the most common questions related to Scanner and we hope our answers will be helpful to you — now, let’s get started!

Everything You Need to Know About Java Scanner

What is Scanner class in Java?

Scanner is a class in java.util package that is used for parsing primitive types and strings by using regular expressions. Basically it is used for reading input from the command line, although this approach is not very effective for situations where time is limited. For time-sensitive cases it’s preferable to use reading values from a file.

Here is a sample of Scanner source code for a reference:

package java.util;

How to use Scanner in Java?

To use the Scanner class, you’ll need to create a class object and select one of the methods described in the Scanner class documentation.

To get the instance of Java Scanner that reads user input, you’ll have to pass the input stream (System.in) in the constructor of Scanner. 

Scanner scanner = new Scanner (System.in);

To get the instance of Java Scanner that is responsible for strings parsing, you’ll have to pass the strings in the constructor of Scanner. 

Scanner scanner = new Scanner("Hello Softteco");  

Or you may pass an object of class File if we want to read input from a file.

Scanner scanner = new Scanner(new File("Softteco.txt"));

Scanner has a lot of constructors for different types of input. You can find all of them in Scanner.java class.

Scanner(Readable source, Pattern pattern)

Scanner(Readable source)

Scanner(InputStream source)

Scanner(InputStream source, String charsetName)

Scanner(InputStream source, Charset charset)

Scanner(File source)

Scanner(File source, String charsetName)

Scanner(File source, Charset charset)

Scanner(File source, CharsetDecoder dec)

Scanner(Path source)

Scanner(Path source, String charsetName)

Scanner(Path source, Charset charset)

Scanner(String source)

Scanner(ReadableByteChannel source)

Scanner(ReadableByteChannel source, String charsetName)

Scanner(ReadableByteChannel source, Charset charset)

How to import scanner in Java?

Since Scanner belongs to the java.util package, you can import it without downloading any external libraries. There are two ways of how you can do this:

If you plan to work with the java.util.Scanner class only, you can import the Scanner class directly.

import java.util.Scanner;

If you work with other modules in the java.util library, it may be a good idea to import the full library.

import java.util.*;

The first line of code imports the Scanner class. The second line of code imports all the packages within the java.util library, including Scanner.

How to read a file in Java using Scanner?

To read the content of a file, the Scanner class provides the following constructors:

Scanner(InputStream source)

Scanner(InputStream source, String charsetName)

Scanner(InputStream source, Charset charset)

Scanner(File source)

Scanner(File source, String charsetName)

Scanner(File source, Charset charset)

Scanner(File source, CharsetDecoder dec)

Scanner(Path source)

Scanner(Path source, String charsetName)

Scanner(Path source, Charset charset)

You have to use the following Scanner methods for reading information from a file:

scanner.hasNext()  — this method verifies whether the file has another line
scanner.nextLine()  — this method reads and returns the next line in the file.

Example with File Object:

import java.io.File;

import java.util.Scanner;

public class Example {

    public static void main(String args[]) throws Exception {

        //Creating the File object

        File file = new File("D:\Softteco.txt");

        //Creating a Scanner object

        Scanner scanner = new Scanner(file);

        //verify whether the file has another line

        while(scanner.hasNext()) {

            //reads, returns and prints the next line in the file.

            String str = scanner.nextLine();

            System.out.println(str);

        }

    }

}

Example with InputStream Object

public class Example {

    public static void main(String args[]) throws Exception {

        //Creating the File object

        InputStream inputStream = new FileInputStream("D:\Softteco.txt");

        //Creating a Scanner object

        Scanner scanner = new Scanner(inputStream);

        //verify whether the file has another line

        while (scanner.hasNext()) {

            //reads, returns and print the next line in the file.

            String str = scanner.nextLine();

            System.out.println(str);

        }

    }

}

Example with Path Object

public class Example {

    public static void main(String args[]) throws Exception {

        //Creating the File object

        Path source = Paths.get("D:\Softteco.txt");

        //Creating a Scanner object

        Scanner scanner = new Scanner(source);

        //verify whether the file has another line

        while (scanner.hasNext()) {

            //reads, returns and print the next line in the file.

            String str = scanner.nextLine();

            System.out.println(str);

        }

    }

}

How to take input from user in Java using Scanner?

Java Scanner class allows the user to take input from the console. To get the instance of Java Scanner which reads input from the user, we need to pass the input stream (System.in) in the constructor of the Scanner class. 

For Example:

Scanner scanner = new Scanner (System.in);

It helps read the input of primitive types (i.e. int, double, long, short, float, or byte) and is the easiest way to read input in Java. The Java Scanner class provides the following methods to read different primitives types: 

How to take input from user in Java using Scanner?

The following example allows users to read different types of data form the System.in.

import java.util.Scanner;

class Example {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);    

        System.out.print("Enter the integer number- ");

        int a = sc.nextInt();

        System.out.print("Enter the double number- ");

        double b = sc.nextDouble();

        System.out.print("Enter any text- ");

        String c = sc.nextLine();

        System.out.println(a);

        System.out.println(b);

        System.out.println(c);

    }

}

How to close Scanner in Java?

Scanner is a class, where non-memory resources (like file descriptors) are used. So, java garbage collector cannot manage these resources and cannot free them up in order to avoid the resource leak.

There are two ways of keeping Scanner in the correct state in java.

First is using close() method after reading input in finally block. This approach is useful if you’re using a Java version that’s earlier than JDK 7.

Scanner keyboard = new Scanner(System.in);

try{

   keyboard.nextLine();

}finally {

   keyboard.close();

}

A more correct way is to use try-with-resources construction, which was introduced in JDK 7.

try (Scanner keyboard = new Scanner(System.in)) {

// do your scanner stuff

}

In this case, Java will handle the process of closing resources automatically and the developer will not have to worry about closing the Scanner implicitly.

How to import a Scanner in Java?

For importing Scanner, we’ll use a standard operator import as there is no other way to do so in Java.

import java.util.Scanner;

How to read multiple string input in Java?

There might be cases when you need to read a non-defined number of strings from CLI. In this case you can use the following example:

Scanner sc = new Scanner(System.in);

            while(sc.hasNextLine()){

                System.out.println(sc.nextLine());

            }

But in this case you won’t get out of the while loop, so for using this example you have to think of the condition when reading from the scanner will be finished. For instance, you would want to check if еру input string contains еру word «finish» and then break the while.

Scanner sc = new Scanner(System.in);

            StringBuilder builder = new StringBuilder();

            while(sc.hasNextLine()){

                builder.append(sc.nextLine());

                System.out.println(builder.toString());

                if(builder.toString().contains("finish")) break;

            }

            builder.setLength(0);

How to read user input in Java without using  Scanner?

Are there alternative ways of reading input from users without using a Scanner in java? Definitely, there are. For example, here is sample with InputStreamReader

InputStreamReader reader = new InputStreamReader(System.in);

BufferedReader br = new BufferedReader(reader);

System.out.println("Whis is our name?");

var input = br.readLine();

System.out.println("Your input was: " + input);

But in fact it doesn’t matter which approach you’re using (either with Scanner or with InputStreamReader), because in both cases you will have to pass  System.in input stream to the constructor.

How to close Scanner in Java?

Class Scanner has a method named close(). This method does not take any arguments and returns nothing. It just closes the current scanner instance.

The invocation of this method will have no effect if the Scanner is already closed.

Why we need to close it?

Once you perform the operations on Scanner, you should close it. Otherwise, Scanner will be opened and it is available to pass any info to the application and may cause data leaks.

Example:

import java.util.Scanner;

public class ScannerExample {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        System.out.println("Enter current day");

        int day = scanner.nextInt();

        System.out.println("Enter current month");

        String month = scanner.next();

//closing Scanner instance.

        scanner.close();

        System.out.println("Date now : " + day + " " + month);

    }

}

After closing instance of Scanner you can’t use it. Otherwise you will get IllegalStateException.

Example:

public class ScannerExample {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        System.out.println("Enter current day");

        int day = scanner.nextInt();

        System.out.println("Enter current month");

        String month = scanner.next();

//closing Scanner instance

        scanner.close();

System.out.println("Enter current year");

//trying to enter current year

        int year = scanner.nextInt();

        System.out.println("Date now : " + day + " " + month + " " + year);

    }

}

The result will be:

How to take input from user in Java using Scanner?

The most correct way to close a Scanner instance is to use try/catch/finally block. Because classes which utilize non-memory resources should provide ways to explicitly allocate/deallocate those resources. We need to explicitly call close() methods for deallocation of file descriptors in finally{}, as it will execute whether or not an exception is thrown.

Example: 

import java.util.Scanner;

public class ScannerExample {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        int day = 0, year = 0;

        String month = "";

        try {

            System.out.println("Enter current day");

            day = scanner.nextInt();

            System.out.println("Enter current month");

            month = scanner.next();

            System.out.println("Enter current year");

            year = scanner.nextInt();

        } catch (Exception e) {

            e.printStackTrace();

        } finally {

            scanner.close();

            System.out.println("Scanner was closed");

        }

        System.out.println("Date now : " + day + " " + month + " " + year);

    }

}

The result:

How to clear Scanner in Java?

Honestly, you can’t really clear Scanner’s buffer. Internally, it may clear the buffer after a token is read, but that’s an implementation detail outside of the programmers’ reach.

How to loop a Scanner in Java?

You have many ways to loop: using for(), while or different methods of Scanner class if you want to control data which is input by the user.

Example 1: User must input only a word and then display it. (Used while loop)

import java.util.Scanner;

public class ScannerExample {

    public static void main(String[] args) {

        try (Scanner scanner = new Scanner(System.in)) {

            ArrayList<String> allWords = new ArrayList<>();

            String word = "";

    // here we use while loop to control input of user

    // and add every word to list of words 

    // when user input stop scanner closed

    // then we can see all words.

            while (!word.equalsIgnoreCase("stop")) {

                System.out.println("Input word");

                word = scanner.next();

                if (!word.equalsIgnoreCase("stop")) {

                    allWords.add(word);

                }

            }

            System.out.println("Your words:" + allWords);

        } catch (Exception e) {

            e.printStackTrace();

        } finally {

            System.out.println("Scanner was closed");

        }

    }

}

The result:

How to loop a Scanner in Java?

Example 2: User must input number until result of multiplying will be bigger than 100. (Used for loop)

public class ScannerExample {

    public static void main(String[] args) {

        try (Scanner scanner = new Scanner(System.in)) {

            int value;

            int result;

            for (result = 1; result < 100; result = result * value) {

                System.out.println("Input number");

                value = scanner.nextInt();

            }

            System.out.println("The result of multiplying: " + result);

        } catch (Exception e) {

            e.printStackTrace();

        } finally {

            System.out.println("Scanner was closed");

        }

    }

}

The result:

Example 3: Read words from a file until they run out (Using methods of Scanner).

import java.io.File;

import java.util.Scanner;

public class ScannerExample {

    public static void main(String[] args) {

        File file = new File("Cities.txt");

        try {

            Scanner scanner = new Scanner(file);

            System.out.println("Cities from file: ");

            while (scanner.hasNext()) {

                String city = scanner.next();

                System.out.println(city);

            }

        } catch (Exception e) {

            e.printStackTrace();

        } finally {

            System.out.println("Scanner was closed");

        }

    }

}

The result:

An important note! When you create a file object, you need to specify a pathname to this file. In example we put Cities.txt file in the root of the project. If you want to read file from directory from PC you can do something like this:

File file = new File("C:/Users/MyUser/Cities.txt");

Summing up

Whew, that was a lot of information on Java Scanner and we hope you found it useful. Let us know whether you have any other unanswered questions in the comments below — or share your ideas about development tips that we can review next!

Want to stay updated on the latest tech news?

Sign up for our monthly blog newsletter in the form below.

Softteco Logo Footer