Java Scanner Class – Methods and Constructors

In our previous article, we discussed the implements keyword in Java. In this article, we will discuss a special class in Java which is the Java Scanner Class.

Till now, we learned how to print something on the user’s screen with a Java program. But, if you wish to take input from the user while writing a program, then you can use the Scanner class of Java.

In this article, we will learn about this class along with its methods and will understand them with example code snippets and programs.

Scanner Class in Java

The Scanner class in Java is a predefined class that helps us to take input from the user. This class is present in the java.util package and we need to import this package inside our Java program to use this class.

There are many predefined methods in the java.util.Scanner class for performing various operations like reading and parsing various primitive types. Basically, we have to create the object of the Scanner class to use these methods.

The Scanner class can also parse strings and primitive types by using regular expressions.

The Scanner class in Java extends the Object class and implements the Cloneable and Iterator interfaces.

Importing Java Scanner Class

To use the methods and functionalities of the Scanner class, we need to include the class in our Java program by importing the java.util package using the import keyword at the beginning of the code.

We can do it in two ways:

1. import java.util.Scanner;
//imports the Scanner class

2. import java.util.*;
//imports all the classes of java.util package

Using Scanner Class in Java

After importing the Scanner class, we have to get the instance of the Scanner class to read the input from the user. We will create an instance and we will pass the Input Stream System.in while creating the instance as follows:

Scanner scannerObject = new Scanner(System.in);

Here, by writing the Scanner scannerObject, we are declaring the scannerObject as the object of the scanner class. System.in denotes that the input will be given to the System.

Constructors of Java Scanner Class

The Scanner class contains the constructors for specific purposes that we can use in our Java program.

S.N. Constructor Description
1) Scanner(File source) This constructor creates a Scanner object that produces values scanned from the specified file.
2) Scanner(File source, String charsetName) This constructor constructs a new Scanner object that produces values scanned from the specified file.
3) Scanner(InputStream source) This constructor creates a new Scanner object that produces values scanned from the specified input stream.
4) Scanner(InputStream source, String charsetName) This constructor creates a new Scanner that produces values scanned from the specified input stream.
5) Scanner(Readable source) This constructor creates a new Scanner that produces values scanned from the specified source.
6) Scanner(String source) This constructor creates a new Scanner that produces values scanned from the specified string.
7) Scanner(ReadableByteChannel source) This constructor creates a new Scanner that produces valgues scanned from the specified channel.
8) Scanner(ReadableByteChannel source, String charsetName) This constructor creates a new Scanner that produces values scanned from the specified channel.
9) Scanner(Path source) This constructor creates a new Scanner that produces values scanned from the specified file.
10) Scanner(Path source, String charsetName) This constructor creates a new Scanner that produces values scanned from the specified file.

Methods of Java Scanner Class

Now, we will discuss some important methods of the Scanner class without which taking the input is impossible.

Following is the list of methods that we use for various data types.

Method Description
boolean nextBoolean() This method reads the boolean value from the user.
byte nextByte() It reads the byte value from the user.
double nextDouble() It accepts the input in double datatype from the user.
float nextFloat() It takes the float value from the user.
int nextInt() It scans the input in the int type from the user.
String nextLine() This method reads the String value from the user.
long nextLong() This method reads the long type of value from the user.
short nextShort() It reads the short type of value from the user.
char next() It reads the character input from the user.

Code to understand the above methods

Let’s see a single java program that uses all the above-mentioned methods of the Scanner class:

Code to read data of various types using Scanner class:

package com.techvidvan.scannerclass;
import java.util.Scanner;
public class ScannerMethodDemo {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System. in );
    System.out.println("Taking inputs from user");
    System.out.println("Enter name of the Employee:");
    // String input 
    String name = sc.nextLine();
    System.out.println("Enter post:");
    String post = sc.nextLine();
    System.out.println("Enter gender:");
    // Character input 
    char gender = sc.next().charAt(0);

    // Numerical data input 
    System.out.println("Enter age:");
    int age = sc.nextInt();
    System.out.println("Enter mobile number:");
    long mobileNo = sc.nextLong();
    System.out.println("Enter salary");
    double salary = sc.nextDouble();

    // Print the values to check if the input was correctly obtained. 
    System.out.println("\nName: " + name);
    System.out.println("Post: " + post);
    System.out.println("Gender: " + gender);
    System.out.println("Age: " + age);
    System.out.println("Mobile Number: " + mobileNo);
    System.out.println("Salary: " + salary);
  }
}

Output

Taking inputs from the user
Enter the name of the Employee:
Avina Garg
Enter post:
Research Analyst
Enter gender:
F
Enter age:
23
Enter mobile number:
95687968756
Enter salary
30000.00
Name: Avina Garg
Post: Research Analyst
Gender: F
Age: 23
Mobile Number: 95687968756
Salary: 30000.00

Java hasNextDataType() Methods

There are times when we need to check if the next value we read is of a certain type or if the input has EOF or not. Then, we check if the scanner’s input is of the type we want with the help of hasNextXYZ() functions where XYZ is the datatype we want to use.

The method returns true if the scanner has a token of that type, otherwise returns false. There are some boolean methods for each data type.to check whether the next token of a particular data type is available in the given input or not. The following table shows them:

Method  Description
boolean hasNextBoolean() This method checks if the next token in this scanner’s input  interprets as a Boolean using the nextBoolean() method or not.
boolean hasNextByte() This method checks if the next token in this scanner’s input interprets as a Byte using the nextByte() method or not.
boolean hasNextDouble() This method checks whether the next token in this scanner is a BigDecimal input using the nextBigDecimal() method or not.
boolean hasNextFloat() This method checks whether the next token in this scanner’s input interprets as a Float using the nextFloat() method or not.
boolean hasNextInt() This method checks whether the next token in this scanner’s input interprets as an int using the nextInt() method or not.
boolean hasNextLine() This method checks whether there is another line in the input of this scanner or not.
boolean hasNextLong() This method checks whether the next token in this scanner’s input interprets as a Long using the nextLong() method or not.
boolean hasNextShort() This method checks whether the next token in this scanner’s input interprets as a Short using the nextShort() method or not.

Code to read some values using Scanner class and print their mean:

package com.techvidvan.scannerclass;
import java.util.Scanner;
public class ScannerMethodsDemo1 {
  public static void main(String[] args) {
    System.out.println("Enter the numbers and any character other than an integer to get their mean:");
    Scanner sc = new Scanner(System. in );

    // Initialize sum and count of input elements 
    int sum = 0,
    count = 0;

    //Checking if an int value is available 
    while (sc.hasNextInt()) {
      // Read an int value 
      int num = sc.nextInt();
      sum += num;
      count++;
    }
    int mean = sum / count;
    System.out.println("Mean of the numbers is: " + mean);
  }
}

Output

Enter numbers and any character other than an integer to get the Mean of numbers:
2
4
6
4
10
24
57
80
A
Mean of the numbers is: 26

Working of Java Scanner class

The Scanner class reads an entire line and divides the line into tokens. Tokens are small elements that have some meaning to the Java compiler.

Suppose there is an input string:

His age is 23

In this case, the scanner object will read the entire line and divide the string into tokens: “His”, “age” “is” and “23”. The object then iterates over each token and reads each token using its different methods.

Note: By default, the use of whitespace is to divide tokens.

String Tokenization using the Scanner class

Java Scanner class is also used to parse the string into tokens and perform operations on them. There are some useful methods provided by the Scanner class to do this. These methods are:

Method Description
Stream<String> tokens() This method gives a stream of delimiter-separated tokens from the Scanner object which is in use.
String toString() This method returns the string representation of Scanner using.
Scanner useDelimiter() This method sets the delimiting pattern of the Scanner which is in use to the specified pattern.
void close() This method closes this scanner.

Code to understand the String Tokenization with the Scanner class:

Example 1:

package com.techvidvan.scannerclass;
import java.util.Scanner;
public class ScannerTokens1 {
  public static void main(String args[]) {
    String s = "Techvidvan%Java%Tutorials%Scanner%program%3";
    //Initialize Scanner object 
    Scanner sc = new Scanner(s);
    //Initialize the string delimiter  
    sc.useDelimiter("%");
    //Prints stream of delimiter-separated tokens  
    sc.tokens();
    //Printing the tokenized Strings  
    while (sc.hasNext()) {
      System.out.println(sc.next());
    }
    sc.close();
  }
}

Output

Techvidvan
Java
Tutorials
Scanner
program
3

Example 2:

package com.techvidvan.scannerclass;
import java.util.Scanner;
public class ScannerTokens2 {
  public static void main(String args[]) {
    String input = "5 Java 2 Java techvidvan Java tutorial Java";@SuppressWarnings("resource")
    Scanner sc = new Scanner(input).useDelimiter("\\s*Java\\s*");
    // \\s* means 0 or more repetitions of any whitespace character   
    //Java is the pattern to find 
    sc.tokens();
    System.out.println(sc.nextInt()); // prints: 5  
    System.out.println(sc.nextInt()); // prints: 2  
    System.out.println(sc.next()); // prints: techvidvan  
    System.out.println(sc.next()); // prints: tutorial         
    //close the scanner  
    sc.close();
  }
}

Output

5
2
techvidvan
tutorial

Example 3:

import java.util. * ;
public class ScannerTokens3 {
  public static void main(String args[]) {
    String myStr = "Hello/This is TechVidvan/Java Tutorials/Scanner class";
    //Create a scanner class object with the specified String  
    Scanner scanner = new Scanner(myStr);
    //Changing the delimiter of this scanner  
    scanner.useDelimiter("/");
    //Printing the tokenized Strings  
    System.out.println("---The Tokenized Strings are---");
    while (scanner.hasNext()) {
      System.out.println(scanner.next());
    }
    //Displaying the new delimiter  
    System.out.println("Delimiter used: " + scanner.delimiter());
    scanner.close();
  }
}

Output

—The Tokenized Strings are—
Hello
This is TechVidvan
Java Tutorials
Scanner class
Delimiter used: /

Conclusion

This was all about Java Scanner class. The Scanner class plays a very important role in taking inputs from the user. It is present in the java.util package and comes with various constructors and methods to take inputs of all types of primitive data types and String types.

It is also helpful in tokenizing the strings. We have discussed the concepts with examples for your better understanding. We hope this article will be helpful in studying the Scanner class in Java.

TechVidvan Team

The TechVidvan Team delivers practical, beginner-friendly tutorials on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our experts are here to help you upskill and excel in today’s tech industry.