- Java.util - Home
- Java.util - ArrayDeque
- Java.util - ArrayList
- Java.util - Arrays
- Java.util - BitSet
- Java.util - Calendar
- Java.util - Collections
- Java.util - Currency
- Java.util - Date
- Java.util - Dictionary
- Java.util - EnumMap
- Java.util - EnumSet
- Java.util - Formatter
- Java.util - GregorianCalendar
- Java.util - HashMap
- Java.util - HashSet
- Java.util - Hashtable
- Java.util - IdentityHashMap
- Java.util - LinkedHashMap
- Java.util - LinkedHashSet
- Java.util - LinkedList
- Java.util - ListResourceBundle
- Java.util - Locale
- Java.util - Observable
- Java.util - PriorityQueue
- Java.util - Properties
- Java.util - PropertyPermission
- Java.util - PropertyResourceBundle
- Java.util - Random
- Java.util - ResourceBundle
- Java.util - ResourceBundle.Control
- Java.util - Scanner
- Java.util - ServiceLoader
- Java.util - SimpleTimeZone
- Java.util - Stack
- Java.util - StringTokenizer
- Java.util - Timer
- Java.util - TimerTask
- Java.util - TimeZone
- Java.util - TreeMap
- Java.util - TreeSet
- Java.util - UUID
- Java.util - Vector
- Java.util - WeakHashMap
- Java.util - Interfaces
- Java.util - Exceptions
- Java.util - Enumerations
- Java.util Useful Resources
- Java.util - Useful Resources
- Java.util - Discussion
Scanner Class in Java
Introduction
The Java Scanner class is a simple text scanner that can parse primitive types (int, double, long, etc.) and strings using regular expressions. The Scanner class plays an important role in Java by providing user-based input.
The Scanner class is a part of java.util package, and a scanner can read text from any object that implements the Readable interface. When we close a Scanner, it will close its input source if the source implements the Closeable interface.
Characteristics of the Scanner class
The following are some of the important characteristics of the Scanner class in Java −
- A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.
- A scanning operation may block while waiting for input.
- A Scanner is not safe for multithreaded use without external synchronization.
Class declaration
F ollowing is the declaration for the Scanner class −
public final class Scanner extends Object implements Iterator<String>
How to use the Scanner Class?
The scanner class can be used by following the steps below −
Step 1
The first and important step is to import the java.util.Scanner at the top of our code, as without the Scanner class, we cannot use its methods. We can either use the java.uti.Scanner or java.util.* package to work with the Scanner class.
import java.util.Scanner //OR import java.util.*
Step 2
The second step is to create the object of the Scanner class. Here, the "sc" is the Scanner class object, and it allows the user to read from the System. To create an object of the Scanner class, call the Scanner() constructor.
Scanner sc = new Scanner(System.in);
Step 3
The third step is to create a variable, and on that variable, use the methods from the Scanner class object to take user input.
int number = sc.nextInt();
After using the Scanner class, use the close() method to close the Scanner operations.
Example
Below is an example of how to input a number using the Scanner class in Java −
//Step 1: import the Scanner class
import java.util.Scanner;
public class DemoScanner {
public static void main(String[] args) {
// Step 2: Create Scanner object
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
// Step 3: Read the number from console
int number = sc.nextInt();
System.out.println("The entered number is: " + number);
// Close the scanner
sc.close();
}
}
Output
This will produce the following result −
Enter a number: 10 The entered number is: 10
Uses of Scanner Class
The following are some of the use cases of the Scanner class in Java −
- The Scanner class is used for reading and analyzing data stored in text files(logs, configuration files).
- Helps developers in building console-based applications, such as a Student management system.
- It can also be used to parse tokens, which helps in Data Parsing from CSV files.
Class constructors
The following are the Scanner class constructors present in Java −
| Sr.No. | Constructor & Description |
|---|---|
| 1 |
Scanner(File source) This constructs a new Scanner that produces values scanned from the specified file. |
| 2 |
Scanner(File source, String charsetName) This constructs a new Scanner that produces values scanned from the specified file. |
| 3 |
Scanner(File source, Charset charset) This constructs a new Scanner that produces values scanned from the specified file. |
| 4 |
Scanner(InputStream source) This constructs a new Scanner that produces values scanned from the specified input stream. |
| 5 |
Scanner(InputStream source, String charsetName) This constructs a new Scanner that produces values scanned from the specified input stream. |
| 6 |
Scanner(InputStream source, Charset charset) This constructs a new Scanner that produces values scanned from the specified input stream. |
| 7 |
Scanner(Readable source) This constructs a new Scanner that produces values scanned from the specified source. |
| 8 |
Scanner(String source) This constructs a new Scanner that produces values scanned from the specified source. |
| 9 |
Scanner(ReadableByteChannel source) This constructs a new Scanner that produces values scanned from the specified channel. |
| 10 |
Scanner(ReadableByteChannel source, String charsetName) This constructs a new Scanner that produces values scanned from the specified channel. |
| 11 |
Scanner(ReadableByteChannel source, Charset charset) This constructs a new Scanner that produces values scanned from the specified channel. |
| 12 |
Scanner(Path source) This constructs a new Scanner that produces values scanned from the specified file. |
| 13 |
Scanner(Path source, String charsetName) This constructs a new Scanner that produces values scanned from the specified file. |
| 14 |
Scanner(Path source, Charset charset) This constructs a new Scanner that produces values scanned from the specified file. |
Class methods
The following are the Scanner class methods present in Java −
| Sr.No. | Method & Description |
|---|---|
| 1 |
void close()
This method closes this scanner. |
| 2 |
Pattern delimiter()
This method returns the Pattern this Scanner is currently using to match delimiters. |
| 3 |
Stream<MatchResult> findAll(String patString)
This method returns a stream of match results that match the provided pattern string. |
| 4 |
String findInLine(Pattern pattern)
This method attempts to find the next occurrence of the specified pattern, ignoring delimiters. |
| 5 |
String findWithinHorizon(Pattern pattern, int horizon)
This method attempts to find the next occurrence of the specified pattern. |
| 6 |
boolean hasNext()
This method returns true if this scanner has another token in its input. |
| 7 |
boolean hasNextBigDecimal()
This method returns true if the next token in this scanner's input can be interpreted as a BigDecimal using the nextBigDecimal() method. |
| 8 |
boolean hasNextBigInteger()
This method returns true if the next token in this scanner's input can be interpreted as a BigInteger in the default radix using the nextBigInteger() method. |
| 9 |
boolean hasNextBoolean()
This method returns true if the next token in this scanner's input can be interpreted as a boolean value using a case-insensitive pattern created from the string "true|false". |
| 10 |
boolean hasNextByte()
This method returns true if the next token in this scanner's input can be interpreted as a byte value in the default radix using the nextByte() method. |
| 11 |
boolean hasNextDouble()
This method returns true if the next token in this scanner's input can be interpreted as a double value using the nextDouble() method. |
| 12 |
boolean hasNextFloat()
This method returns true if the next token in this scanner's input can be interpreted as a float value using the nextFloat() method. |
| 13 |
boolean hasNextInt()
This method returns true if the next token in this scanner's input can be interpreted as an int value in the default radix using the nextInt() method. |
| 14 |
boolean hasNextLine()
This method returns true if there is another line in the input of this scanner. |
| 15 |
boolean hasNextLong()
This method returns true if the next token in this scanner's input can be interpreted as a long value in the default radix using the nextLong() method. |
| 16 |
boolean hasNextShort()
This method returns true if the next token in this scanner's input can be interpreted as a short value in the default radix using the nextShort() method. |
| 17 |
IOException ioException()
This method returns the IOException last thrown by this Scanner's underlying Readable. |
| 18 |
Locale locale()
This method returns this scanner's locale. |
| 19 |
MatchResult match()
This method returns the match result of the last scanning operation performed by this scanner. |
| 20 |
String next()
This method finds and returns the next complete token from this scanner. |
| 21 |
BigDecimal nextBigDecimal()
This method scans the next token of the input as a BigDecimal. |
| 22 |
BigInteger nextBigInteger()
This method scans the next token of the input as a BigInteger. |
| 23 |
boolean nextBoolean()
This method scans the next token of the input into a Boolean value and returns that value. |
| 24 |
byte nextByte()
This method scans the next token of the input as a byte. |
| 25 |
double nextDouble()
This method scans the next token of the input as a double. |
| 26 |
float nextFloat()
This method scans the next token of the input as a float. |
| 27 |
int nextInt()
This method scans the next token of the input as an int. |
| 28 |
String nextLine()
This method advances this scanner past the current line and returns the input that was skipped. |
| 29 |
long nextLong()
This method scans the next token of the input as a long. |
| 30 |
short nextShort()
This method scans the next token of the input as a short. |
| 31 |
int radix()
This method returns this scanner's default radix. |
| 32 |
void remove()
The remove operation is not supported by this implementation of Iterator. |
| 33 |
Scanner reset()
This method resets this scanner. |
| 34 |
Scanner skip(Pattern pattern)
This method skips input that matches the specified pattern, ignoring delimiters. |
| 35 |
Stream<String> tokens()
Returns a stream of delimiter-separated tokens from this scanner. |
| 36 |
String toString()
This method returns the string representation of this Scanner. |
| 37 |
Scanner useDelimiter(Pattern pattern)
This method sets this scanner's delimiting pattern to the specified pattern. |
| 38 |
Scanner useLocale(Locale locale)
This method sets this scanner's locale to the specified locale. |
| 39 |
Scanner useRadix(int radix)
This method sets this scanner's default radix to the specified radix. |
Methods inherited
This class inherits methods from the following classes −
Reading a Line from Console using Scanner Class Example
The following example shows the usage of Java Scanner nextLine() to read a line from the Console and the close() method to close the scanner. We've created a scanner object using a given string. Then we printed the string using the nextLine() method, and then the scanner was closed using the close() method.
package com.tutorialspoint;
import java.util.Scanner;
public class ScannerDemo {
public static void main(String[] args) {
String s = "Hello World! 3 + 3.0 = 6";
// create a new scanner with the specified String Object
Scanner scanner = new Scanner(s);
// print the next line of the string
System.out.println(scanner.nextLine());
// close the scanner
System.out.println("Closing Scanner...");
scanner.close();
System.out.println("Scanner Closed.");
}
}
Output
This will produce the following result −
Hello World! 3 + 3.0 = 6 Closing Scanner... Scanner Closed.
Handling Mixed Inputs in Scanner Class
When working with multiple inputs like nextInt(), nextDouble(), nextFloat(), they do not need a newline (\n) character after pressing the Enter key. This creates a problem when taking string input after them, as they take an empty string between them, creating issues in the code. So, to handle this issue, always add a sc.nextLine() in between number and string inputs.
Example
Below is an example for handling mixed inputs using the Scanner Class in Java −
import java.util.Scanner;
public class ScannerDemo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter your age: ");
int age = sc.nextInt();
// Handling the newline issue
sc.nextLine();
System.out.print("Enter your name: ");
String name = sc.nextLine();
System.out.print("Enter your salary: ");
double salary = sc.nextDouble();
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Salary: " + salary);
sc.close();
}
}
Output
This will produce the following result −
Enter your age: 23 Enter your name: Akash Enter your salary: 23403.75 Name: Akash Age: 23 Salary: 23403.75