Scanner in Java | Methods, Example

Scanner in Java is a predefined class that reads or scans the data dynamically from the keyboard or a text file.

In other words, Scanner class allows the user to read all types of numeric values, strings, and other types of data in java, whether it comes from a disk file, keyboard, or another source.

It is the fastest and easiest way to receive the input from the user in java than InputStreamReader and BufferedReader.

Scanner is a new util class that was added in Java 1.5 to simplify the task of getting input from the user. It is present in java.util.Scanner package.

This class is really useful for handling the input from the keyboard, console, text file, or any source that implements the Readable interface or ReadableByteChannel.

For example, we can use the Scanner class to read a number from the keyboard and assign its value to a variable.

Java Scanner class declaration


Scanner is a final class that extends Object class and implements Closeable, AutoCloseable, and Iterator<String> interfaces. The general syntax to declare scanner class in java is as follows:

public final class Scanner
   extends Object
         implements Iterator<String>, Closeable

It is recommended that we must import Scanner class into the java program before using Scanner class. The statement to import scanner class is as follows:

import java.util.Scanner;
Or,
import java.util.*;

Constructors of Scanner class for creating Scanner Object


Scanner class provides several different constructors for creating a scanner object. They are as follows:

1. Scanner(File file): This constructor creates a Scanner object with the specified file object as a source for input. The general syntax to create an object of Scanner class that will read the file myfile.txt, as follows:

FileReader fr = new FileReader("myfile.txt");
Scanner sc = new Scanner(fr); // It will read data from myfile.txt file.

It will throw FileNotFoundException if the source is not found.

2. Scanner(File file, String charsetName): This form of overloading constructor creates a Scanner object with the specified file object as a source for input and charset. Here, charsetName is the encoding type used to convert bytes from the file into characters.

3. Scanner(InputStream is): This constructor creates a Scanner object with the specified InputStream is as a source for input.

The general syntax to create an object of Scanner class in Java with specified input stream, as follows:

Scanner sc = new Scanner(System.in); // Here, System.in is an object of type InputStream. 
The sc object reads the user input from System.in (i.e. keyboard).

4. Scanner(InputStream is, String charsetName): This overloading constructor creates a Scanner object with the specified input stream and charset.


5. Scanner(Path path): This constructor constructs an object of Scanner class with the specified path as a source for input.


6. Scanner(Path path, String charsetName): This constructor creates a new Scanner with the specified path and charset.

7. Scanner(Readable rd): This constructor creates a Scanner object with the specified readable object as a source for input.

8. Scanner(ReadableByteChannel rByteChannel): This constructor constructs a Scanner object with the specified channel as a source for input.


9. Scanner(ReadableByteChannel rByteChannel, String charsetName): This overloading constructor creates a Scanner object with the specified channel and charset.

10. Scanner(String str): This form of constructor creates an object of Scanner with the specified string str as a source for input.

How does Java Scanner read Input from keyboard?


Scanner class receives data in token form. When it accepts input, it breaks the input into several pieces, called tokens using a delimiter that is whitespace by default.

For example, if we read a series of numbers separated by blank spaces, the scanner class will take each number as a separate token.

These tokens are retrieved from an object of Scanner class by using the scanner methods.

For example, suppose we want to read an integer value as input from the keyboard, we will create an object of Scanner class as:

Scanner sc = new Scanner(System.in);

Now, entered integer value is stored in Scanner object (sc) as a token. To retrieve that token, we will call the nextInt() method like this:

int value = sc.nextInt(); // It just reads the number.

The token automatically converts into a value of the byte, short, int, long, float, or double type for nextByte(), nextShort(), nextInt(), nextLong(), nextFloat(), and nextDouble(), respectively.

No conversion is done for the next() method. If the token does not match with the expected type, a runtime exception named InputMismatchException will be thrown.


Notes:

a) Token: A token is a series of characters that ends with whitespace characters like blank, a tab character, and a carriage return.

b) Delimeter: A delimiter is a character (, ;, :, etc.) that is used to separate items of data stored on a computer. It tells the computer to finish processing one item of data and move on to the next one.

Scanner Class Methods in Java


In addition to methods inherited from Object class, Scanner class provides several different methods to handle numeric and string data. They are as follows:

List of Scanner hasNext methods:

1. boolean hasNext( ): This method returns true if another token is available to be read. Otherwise returns false.

2. boolean hasNext(Pattern pattern): This method returns true if the next token matches with the specified pattern available to be read. Returns false otherwise.

3. boolean hasNext(String pattern): This method returns true if the next token matches with the specified string pattern available to be read. Returns false otherwise.

4. boolean hasNextBigDecimal( ): This method returns true if the next token in Scanner’s input can be stored in a BigDecimal object is available to be read. Otherwise returns false.


5. boolean hasNextBigInteger( ): This method returns true if the next token in Scanner’s input can be stored in a BigInteger object is available to be read.


6. boolean hasNextBoolean( ): It returns true if the next token in Scanner’s input is available in boolean to be read. Otherwise, returns false.

7. boolean hasNextByte( ): It returns true if the next token is available in a byte to be read. Otherwise, returns false. The default radix 10 is used.

8. boolean hasNextByte(int radix): It returns true if the next token is available in a byte with specified radix to be read. Returns false otherwise.

9. boolean hasNextDouble( ): It returns true if the next token is available in double to be read. Returns false otherwise.

10. boolean hasNextFloat( ): This method returns true if the next token is available in float to be read. Otherwise returns false.


11. boolean hasNextInt( ): It returns true if the next token is available in int to be read. Returns false otherwise. The default radix 10 is used.

12. boolean hasNextInt(int radix): It returns true if the next token is available in int with specified radix to be read. Otherwise, returns false.

13. boolean hasNextLine( ): This method returns true if a line of input is available.

14. boolean hasNextLong( ): It returns true if the next token is available in long to be read. Otherwise, returns false. The default radix 10 is used.

15. boolean hasNextLong(int radix): It returns true if the next token is available in long with the specified radix to be read. Returns false otherwise.

16. boolean hasNextShort( ): It returns true if the next token is available in short to be read. The default radix 10 is used.

17. boolean hasNextShort(int radix): It returns true if the next token is available in short with specified radix to be read.


List of Scanner next methods:

1. String next( ): This method is used to enter words. It returns the next token as a string from the input source.

2. String next(Pattern pattern): It returns the next token if it matches with the specified pattern from the input source.

3. BigDecimal nextBigDecimal( ): This method returns the next token as a BigDecimal object.

4. BigInteger nextBigInteger( ): This method returns the next token as a BigInteger object. The default radix 10 is used.

5. BigInteger nextBigInteger(int radix): This method returns the next token (using specified radix) as a BigInteger object.


6. boolean nextBoolean( ): This method returns the next token of the input as a boolean value.

7. byte nextByte( ): This method returns the next token of the input as a byte value. The default radix 10 is used.

8. byte nextByte(int radix): This method returns the next token (using the specified radix) as a byte value.

9. double nextDouble( ): This method returns the next token as a double value. If the next token of the input is not a double, InputMismatchException is thrown.

10. float nextFloat( ): This method returns the next token as a float value. If the next token of the input is not a float or is out of range, InputMismatchException is thrown.


11. int nextInt( ): This method reads numbers. That is, it returns the next token as an int value. If the next token of the input is not an integer, InputMismatchException is thrown. The default radix 10 is used.

12. int nextInt(int radix): This method returns the next token (using the specified radix) as an int value.

13. String nextLine( ): This method is used to enter sentences. It returns the next line of input as a string.

14. long nextLong( ): It returns the next token as a long value. If the next token of the input is not in integer form, InputMismatchException is thrown.

15. short nextShort( ): This method scans the next token of the input as a short. The default radix 10 is used.

16. void close(): It is used to close the scanner object.


Notes:

a) All the above next methods are called token-reading methods because they read tokens separated by delimiters. The token reading methods do not read the delimiter after the token.

b) Both next() and nextLine() methods read a string. The difference between them is that the next() method reads a string delimited by delimiters whereas, nextLine() reads a line ending with a line separator.

Example Program based on Java Scanner class


1. Let’s create a simple program where we will accept input data through the keyboard and display them on the console.

Program source code 1:

package javaPackage;
import java.util.Scanner;

public class ScanData {
public static void main(String[] args) 
{
// Create an object of Scanner class using read input.
  Scanner sc = new Scanner(System.in);	
  
// Reading values.
  System.out.println("Enter an integer number: ");
  int integer = sc.nextInt();
  System.out.println("Enter a long integer number: ");
  long longInteger = sc.nextLong();
  
  System.out.println("Enter a floating point number: ");
  float floatNumber = sc.nextFloat();
  System.out.println("Enter a double data type number: ");
  double doubleNumber = sc.nextDouble();
  
  System.out.println("Enter a string: ");
  String str = sc.nextLine();
  
  System.out.println("Entered data: ");
  System.out.println("Integer number: " +integer);
  System.out.println("Long integer number: " +longInteger);
  
  System.out.println("Floating point number: " +floatNumber);
  System.out.println("Double data type number: " +doubleNumber);
  System.out.println("String: " +str);
  sc.close();
 }
}
Output:
            Enter an integer number: 100
            Enter a long integer number: 253646747
            Enter a floating point number: 200.50
            Enter a double data type number: 244444444444.55555
            Enter a string: 

            Entered data: 
            Integer number: 100
            Long integer number: 253646747
            Floating point number: 200.5
            Double data type number: 2.4444444444455554E11
            String: 

In this example program, we have created Scanner object to enter both numeric and string data through the keyboard and display them on the console.

In the above output, you will notice an empty string in the last line. Why? Here is the reason.

The token-reading method nextDouble() reads the double value and stops at the delimiter. The nextLine() method returns the string read before the line separator (Enter key). Since there are no strings before the line separator, the line is empty.


2. Let’s take a simple example program where we will read data from the myfile.txt file.

Program source code 2:

package javaPackage;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ScanData {
public static void main(String[] args) throws FileNotFoundException 
{
// Create an object of File class.
     File file = new File("D:\\myfile.txt");	

// Create an object of Scanner class for the file.
     Scanner sc = new Scanner(file);
  
// Reading data from the file.
    while (sc.hasNext()) 
    {
      String firstName = sc.next();
      String mName = sc.next();
      String lastName = sc.next();

      int age = sc.nextInt();
      System.out.println(firstName + " " + mName + " " + lastName + " " + age);
 }
// Close the file
      sc.close();
 }
}
Output:
           John T Smith 50
           Eric K Smith 45

Data written into file:

John T Smith 50
Eric K Smith 45

In this program, each iteration in the while loop reads the first name, middle name, last name, and age from the text file. The file is closed using close() method.

It is not essential to close the input file, but it is a good practice to do so to release the resources occupied by the file.


3. Let’s create a program to input two numbers and find the sum using numeric methods of Java Scanner class.

Program source code 3:

package javaPackage;
import java.util.Scanner;
public class AddNum {
public static void main(String[] args)
{
  Scanner sc = new Scanner(System.in);
  System.out.println("Enter your first number: ");
  int num1 = sc.nextInt();
  System.out.println("Enter your second number: ");
  int num2 = sc.nextInt();
  
  int sum = num1 + num2;
  System.out.println("Sum: " +sum);
  sc.close();
 }
}
Output:
           Enter your first number: 50
           Enter your second number: 60
           Sum: 110

4. Let’s take an example program where we will enter roll no, name, and id through the keyboard and display them on the console.

Program source code 4:

package javaPackage;
import java.util.Scanner;
public class StudentData {
public static void main(String[] args)
{
  Scanner sc = new Scanner(System.in);
  System.out.println("Enter your roll number: ");
  int rollNo = sc.nextInt();
  
  System.out.println("Enter your name: ");
  String name = sc.next(); // It reads a string.
  
  System.out.println("Enter your id: ");
  int id = sc.nextInt();
  System.out.println("Roll no: " +rollNo+ " Name: " +name+ " Id: " +id);
  sc.close();
  }
}
Output:
            Enter your roll number: 02
            Enter your name: Deep
            Enter your id: 264547
            Roll no: 2 Name: Deep Id: 264547


5. Let’s create a program to find the maximum out of three numbers using conditional operator (?).

Program source code 5:

package javaPackage;
import java.util.Scanner;
public class GNumber {
public static void main(String[] args)
{
  Scanner sc = new Scanner(System.in);
  int n1, n2, n3, max;
  System.out.println("Enter first number: ");
   n1 = sc.nextInt();
  System.out.println("Enter second number: ");
   n2 = sc.nextInt();
  System.out.println("Enter third number: ");
   n3 = sc.nextInt();
   
   max = ((n1 > n2) ? (n1 > n3) ? n1 : n3 : ((n2 > n3) ? n2 : n3)); 
 
   System.out.println("Greatest number: " +max);
   sc.close();
  }
}
Output:
           Enter first number: 25
           Enter second number: 30
           Enter third number: 10
           Greatest number: 30

6. Let’s take an example program to check if there is an integer, is read or not using hasNextInt() method of Java Scanner class.

Program source code 6:

package javaPackage;
import java.util.Scanner;
public class IntegerRead {
public static void main(String[] args)
{
 int value;	
  Scanner sc = new Scanner(System.in);
  System.out.println("Enter an integer value: "); // Prompt for input.
  
  if(sc.hasNextInt()) // Checking an integer value read or not.
  {
	value = sc.nextInt(); // If so, read the value.
	System.out.println(+value+" is an integer value");
  }
  else{
	System.out.println("You have entered non-integer value");  
  }
  sc.close();
  }
}
Output:
           Enter an integer value: 100
           100 is an integer value.
           Enter an integer value: abcd
           You have entered non-integer value.

In this example program, we have checked both integer and non-integer values are read or not. Similarly, you can also check inputs such as float, double, etc to avoid InputMismatchException.

Character Input through Scanner Class


The scanner class in java does not provide any direct method to get a char input. To get a character from an input, use to charAt() method with next(). Let’s take an example program based on it.

Program source code 7:

package javaPackage;
import java.util.Scanner;
public class CharRead {
public static void main(String[] args)
{
  Scanner sc = new Scanner(System.in);
  System.out.println("Enter a character: ");
  char ch = sc.next().charAt(0);
  System.out.println("Enetered character: " +ch);
  
  System.out.println("Enter a string: ");
  char chr = sc.next().charAt(5); // Extract five character from input string.
  
  System.out.println("Character at index 5: " +chr);
  sc.close();
  }
}
Output:
            Enter a character: D
            Enetered character: D
            Enter a string: Welcome
            Character at index 5: m

Advantages of Scanner class in Java


Scanner class can perform all works that a BufferedReader class does with the same efficiency. There are some advantages of using Scanner class in Java, as follows:

1. No need to use InputStreamReader and BufferedReader to accept data as input from user.

2. The main advantage of using Scanner class is to read primitive type values and string from the keyboard (System.in).

3. Scanner class helps to tokenize the underlying stream with delimiter of our choice.

4. Scanner class is better than BufferedReader to parse some files. BufferedReader is good enough for a simple read operation.

5. Scanner is not thread-safe, but BufferedReader is thread-safe.


Hope that this tutorial has covered almost all the important points concerning with Scanner class in Java with example programs. I hope that you will have understood the simple concepts of Scanner class.
Thanks for reading!!!