(Translated by https://www.hiragana.jp/)
Scanner Class in Java - GeeksforGeeks
Open In App

Scanner Class in Java

Last Updated : 04 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In Java, Scanner is a class in java.util package used for obtaining the input of the primitive types like int, double, etc. and strings.

Using the Scanner class in Java is the easiest way to read input in a Java program, though not very efficient if you want an input method for scenarios where time is a constraint like in competitive programming.

Java Scanner Input Types

Scanner class helps to take the standard input stream in Java. So, we need some methods to extract data from the stream. Methods used for extracting data are mentioned below:

Method

Description

                          nextBoolean()                       

Used for reading Boolean value                    

nextByte()

Used for reading Byte value

nextDouble()

Used for reading Double value

nextFloat()

Used for reading Float value

nextInt()

Used for reading Int value

nextLine()

Used for reading Line value

nextLong()

Used for reading Long value

nextShort()

Used for reading Short value

The Scanner class is widely used for reading user input in Java. For more in-depth examples of handling input and exploring other ways to capture data in Java, the Java Programming Course provides detailed lessons and real-world applications.

Let us look at the code snippet to read data of various data types.

Examples of Java Scanner Class

Example 1:

Java
// Java program to read data of various types 
// using Scanner class.
import java.util.Scanner;

// Driver Class
public class ScannerDemo1 {
      // main function
    public static void main(String[] args)
    {
        // Declare the object and initialize with
        // predefined standard input object
        Scanner sc = new Scanner(System.in);

        // String input
        String name = sc.nextLine();

        // Character input
        char gender = sc.next().charAt(0);

        // Numerical data input
        // byte, short and float can be read
        // using similar-named functions.
        int age = sc.nextInt();
        long mobileNo = sc.nextLong();
        double cgpa = sc.nextDouble();

        // Print the values to check if the input was
        // correctly obtained.
        System.out.println("Name: " + name);
        System.out.println("Gender: " + gender);
        System.out.println("Age: " + age);
        System.out.println("Mobile Number: " + mobileNo);
        System.out.println("CGPA: " + cgpa);
    }
}


Input

Geek
F
40
9876543210
9.9

Output

Name: Geek
Gender: F
Age: 40
Mobile Number: 9876543210
CGPA: 9.9

Sometimes, we have to check if the next value we read is of a certain type or if the input has ended (EOF marker encountered).

Then, we check if the scanner’s input is of the type we want with the help of hasNextXYZ() functions where XYZ is the type we are interested in. The function returns true if the scanner has a token of that type, otherwise false. For example, in the below code, we have used hasNextInt(). To check for a string, we use hasNextLine(). Similarly, to check for a single character, we use hasNext().charAt(0).

Example 2:

Let us look at the code snippet to read some numbers from the console and print their mean. 

Java
// Java program to read some values using Scanner
// class and print their mean.
import java.util.Scanner;

public class ScannerDemo2 {
    public static void main(String[] args)
    {
        // Declare an object and initialize with
        // predefined standard input object
        Scanner sc = new Scanner(System.in);

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

        // Check if an int value is available
        while (sc.hasNextInt()) {
            // Read an int value
            int num = sc.nextInt();
            sum += num;
            count++;
        }
        if (count > 0) {
            int mean = sum / count;
            System.out.println("Mean: " + mean);
        }
        else {
            System.out.println(
                "No integers were input. Mean cannot be calculated.");
        }
    }
}


Input

1 2 3 4 5 

Output

Mean: 3

Important Points About Java Scanner Class

  • To create an object of Scanner class, we usually pass the predefined object System.in, which represents the standard input stream. We may pass an object of class File if we want to read input from a file.
  • To read numerical values of a certain data type XYZ, the function to use is nextXYZ(). For example, to read a value of type short, we can use nextShort()
  • To read strings, we use nextLine().
  • To read a single character, we use next().charAt(0). next() function returns the next token/word in the input as a string and charAt(0) function returns the first character in that string.
  • 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. For example, Suppose there is an input string: How are you
    In this case, the scanner object will read the entire line and divides the string into tokens: “How”, “are” and “you”. The object then iterates over each token and reads each token using its different methods.


Previous Article
Next Article

Similar Reads

Why BufferedReader class takes less time for I/O operation than Scanner class in java
In Java, both BufferReader and Scanner classes can be used for the reading inputs, but they differ in the performance due to their underlying implementations. The BufferReader class can be generally faster than the Scanner class because of the way it handles the input and parsing. This article will guide these difference, provide the detailed expla
3 min read
Difference Between Scanner and BufferedReader Class in Java
In Java, Scanner and BufferedReader class are sources that serve as ways of reading inputs. Scanner class is a simple text scanner that can parse primitive types and strings. It internally uses regular expressions to read different types while on the other hand BufferedReader class reads text from a character-input stream, buffering characters so a
3 min read
Java Deprecated API Scanner tool (jdepscan) in Java 9 with Examples
Java Deprecated API Scanner tool: Java Deprecated API Scanner tool i.e. jdeprscan is a static analyzing command-line tool which is introduced in JDK 9 for find out the uses of deprecated API in the given input. Here the input can be .class file name, directory or JAR file. Whenever we provide any input to jdeprscan command line tool then it generat
2 min read
Scanner nextFloat() method in Java with Examples
The nextFloat() method of java.util.Scanner class scans the next token of the input as a Float(). If the translation is successful, the scanner advances past the input that matched. Syntax: public float nextFloat() Parameters: The function does not accepts any parameter. Return Value: This function returns the Float scanned from the input. Exceptio
4 min read
Scanner skip() method in Java with Examples
skip(Pattern pattern) The skip(Pattern pattern) method of java.util.Scanner class skips input that matches the specified pattern, ignoring the delimiters. The function skips the input if an anchored match of the specified pattern succeeds it. Syntax: public Scanner skip(Pattern pattern) Parameters: The function accepts a mandatory parameter pattern
5 min read
Scanner useRadix() method in Java with Examples
The useRadix(radix) method of java.util.Scanner class sets this scanner's default radix to the specified radix. A scanner's radix affects elements of its default number matching regular expressions. Syntax: public Scanner useRadix(int radix) Parameters: The function accepts a mandatory parameter radix which specifies the radix to use when scanning
2 min read
Scanner close() method in Java with Examples
The close() method ofjava.util.Scanner class closes the scanner which has been opened. If the scanner is already closed then on calling this method, it will have no effect. Syntax: public void close() Return Value: The function does not return any value. Below programs illustrate the above function: Program 1: // Java program to illustrate the // c
1 min read
Scanner delimiter() method in Java with Examples
The delimiter() method ofjava.util.Scanner class returns the Pattern this Scanner is currently using to match delimiters. Syntax: public Pattern delimiter() Return Value: The function returns the scanner's delimiting pattern. Below programs illustrate the above function: Program 1: // Java program to illustrate the // delimiter() method of Scanner
2 min read
Scanner findInLine() method in Java with Examples
findInLine(Pattern pattern) The findInLine(Pattern pattern) method of java.util.Scanner class tries to find the next occurrence of the specified pattern ignoring delimiters. If the pattern is found before the next line separator, the scanner advances past the input that matched and returns the string that matched the pattern. If no such pattern is
4 min read
Scanner useLocale() method in Java with Examples
The useLocale() method of java.util.Scanner class sets this scanner's locale to the specified locale. Syntax: public Scanner useLocale(Locale locale) Parameters: The function accepts a mandatory parameter locale which specifies a string specifying the locale to use. Return Value: The function returns this modified scanner. Exceptions: If the radix
2 min read
Scanner toString() method in Java with Examples
The toString() method of java.util.Scanner class returns the string representation of this Scanner. The exact format is unspecified. Syntax: public String toString() Return Value: This function returns the string representation of this scanner. Below program illustrates the above function: Program 1: // Java program to illustrate the // toString()
1 min read
Scanner useDelimiter() method in Java with Examples
useDelimiter(Pattern pattern) The useDelimiter(Pattern pattern) method of java.util.Scanner class sets this scanner's delimiting pattern to the specified pattern. Syntax: public Scanner useDelimiter(Pattern pattern) Parameter: The function accepts a mandatory parameter pattern which specifies a delimiting pattern. Return Value: The function returns
2 min read
Scanner reset() method in Java with Examples
The reset() method of java.util.Scanner class resets this scanner. On resetting a scanner, it discards all of its explicit state information which may have been changed by invocations of useDelimiter(java.util.regex.Pattern), useLocale(java.util.Locale), or useRadix(int). Syntax: public Scanner reset() Return Value: This function returns this scann
2 min read
Scanner radix() method in Java with Examples
The radix() method of java.util.Scanner class returns this scanner's default radix. Syntax: public int radix() Return Value: This function returns the default radix of this scanner. Below programs illustrate the above function: Program 1: // Java program to illustrate the // radix() method of Scanner class in Java import java.util.*; public class G
2 min read
Scanner nextShort() method in Java with Examples
The nextShort(radix) method of java.util.Scanner class scans the next token of the input as a short. If the translation is successful, the scanner advances past the input that matched. If the parameter radix is not passed, then it behaves similarly as nextShort(radix) where the radix is assumed to be the default radix. Syntax: public short nextShor
5 min read
Scanner nextBigInteger() method in Java with Examples
The nextBigInteger(radix) method of java.util.Scanner class scans the next token of the input as a BigInteger. If the translation is successful, the scanner advances past the input that matched. If the parameter radix is not passed, then it behaves similarly as nextBigInteger(radix) where the radix is assumed to be the default radix. Syntax: public
5 min read
Scanner nextByte() method in Java with Examples
The nextByte(radix) method of java.util.Scanner class scans the next token of the input as a Byte. If the translation is successful, the scanner advances past the input that matched. If the parameter radix is not passed, then it behaves similarly as nextByte(radix) where the radix is assumed to be the default radix. Syntax: public byte nextByte() P
5 min read
Scanner nextInt() method in Java with Examples
The nextInt(radix) method of java.util.Scanner class scans the next token of the input as a Int. If the translation is successful, the scanner advances past the input that matched. If the parameter radix is not passed, then it behaves similarly as nextInt(radix) where the radix is assumed to be the default radix. Syntax: public int nextInt() Parame
5 min read
Scanner nextLong() method in Java with Examples
The nextLong(radix) method of java.util.Scanner class scans the next token of the input as a long. If the translation is successful, the scanner advances past the input that matched. If the parameter radix is not passed, then it behaves similarly as nextLong(radix) where the radix is assumed to be the default radix. Syntax: public long nextLong() P
5 min read
Scanner nextDouble() method in Java with Examples
The nextDouble() method of java.util.Scanner class scans the next token of the input as a Double. If the translation is successful, the scanner advances past the input that matched. Syntax: public double nextDouble() Parameters: The function does not accepts any parameter. Return Value: This function returns the Double scanned from the input. Excep
4 min read
Scanner nextBoolean() method in Java with Examples
The nextBoolean() method of java.util.Scanner class scans the next token of the input as a Boolean. If the translation is successful, the scanner advances past the input that matched. Syntax: public boolean nextBoolean() Parameters: The function does not accepts any parameter. Return Value: This function returns the Boolean scanned from the input.
4 min read
Scanner nextBigDecimal() method in Java with Examples
The nextBigDecimal() method of java.util.Scanner class scans the next token of the input as a BigDecimal. If the next token matches the Decimal regular expression defined above then the token is converted into a BigDecimal value as if by removing all group separators, mapping non-ASCII digits into ASCII digits via the Character.digit, and passing t
4 min read
Scanner nextLine() method in Java with Examples
The nextLine() method of java.util.Scanner class advances this scanner past the current line and returns the input that was skipped. This function prints the rest of the current line, leaving out the line separator at the end. The next is set to after the line separator. Since this method continues to search through the input looking for a line sep
2 min read
Scanner locale() method in Java with Examples
The locale() method of java.util.Scanner class returns this scanner's locale. Syntax: public Locale locale() Parameters: The function does not accepts any parameter. Return Value: This function returns this scanner's locale Below programs illustrate the above function: Program 1: // Java program to illustrate the // locale() method of Scanner class
1 min read
Scanner match() method in Java with Example
The match() method of java.util.Scanner class returns the match result of the last scanning operation performed by this scanner. Syntax: public MatchResult match() Return Value: This function returns a match result for the last match operation. Exceptions: The function throws IllegalStateException if no match has been performed, or if the last matc
2 min read
Scanner ioException() method in Java with Examples
The ioException() method of java.util.Scanner class returns the IOException last thrown by this Scanner's underlying Readable. This method returns null if no such exception exists. Syntax: public IOException ioException() Return Value: This function returns the last exception thrown by this scanner's readable. Below programs illustrate the above fu
2 min read
Scanner hasNextShort() method in Java with Examples
The hasNextShort() method of java.util.Scanner class returns true if the next token in this scanner's input can be assumed as a short value of the given radix. The scanner does not advance past any input. In case no radix is passed as a parameter, the function interprets the radix to be default radix and functions accordingly. Syntax: public boolea
3 min read
Scanner hasNextLong() method in Java with Examples
The hasNextLong() method of java.util.Scanner class returns true if the next token in this scanner's input can be assumed as a Long value of the given radix. The scanner does not advance past any input. In case no radix is passed as a parameter, the function interprets the radix to be default radix and functions accordingly. Syntax: public boolean
3 min read
Scanner hasNextByte() method in Java with Examples
The hasNextByte() method of java.util.Scanner class returns true if the next token in this scanner's input can be assumed as a Byte value of the given radix. The scanner does not advance past any input. In case no radix is passed as a parameter, the function interprets the radix to be default radix and functions accordingly. Syntax: public boolean
3 min read
Scanner hasNextInt() method in Java with Examples
The hasNextInt() method of java.util.Scanner class returns true if the next token in this scanner's input can be assumed as a Int value of the given radix. The scanner does not advance past any input. In case no radix is passed as a parameter, the function interprets the radix to be default radix and functions accordingly. Syntax: public boolean ha
3 min read
Practice Tags :
three90RightbarBannerImg