In Java, there are multiple methods available for obtaining input from users. One of these methods involves utilizing the Scanner class. This approach is considered the most straightforward means of collecting user input. The Scanner class in Java is a component of the java.util package.
The Scanner class divides the input into tokens based on a specified delimiter, with whitespace being the default delimiter. It offers a range of methods for reading and interpreting different primitive data types.
The Scanner class is commonly employed for parsing text to extract strings and primitive data types through regular expressions. This class facilitates reading user input in various primitive types like int, long, double, byte, float, short, and more.
The Java Scanner class is an extension of the Object class and also incorporates the Iterator and Closeable interfaces.
In Java, the Scanner class offers various nextXXX functions to retrieve different types of values like integers using nextInt, bytes using nextByte, shorts using nextShort, strings using next, entire lines using nextLine, double values using nextDouble, float values using nextFloat, boolean values using nextBoolean, and more. If we need to extract a single character from the scanning process, we can utilize the next.charAt(0) operation to obtain a single character.
Java Scanner Class Declaration
public final class Scanner extends Object implements Iterator<String>
How to get a Java Scanner?
In order to create an object of the Java Scanner class that can read user input, it is necessary to provide the input stream (System.in) as an argument in the Scanner class constructor. For instance:
Scanner in = new Scanner(System.in);
In order to obtain an instance of Java Scanner that analyzes strings, it is necessary to provide the strings as arguments in the constructor of the Scanner class. For instance:
Scanner in = new Scanner("Hello Exampletech");
Java Scanner Class Constructors
| Constructor | Description |
|---|---|
| Scanner(File source) | It constructs a new Scanner that produces values scanned from the specified file. |
| Scanner(File source, String charsetName) | It constructs a new Scanner that produces values scanned from the specified file. |
| Scanner(InputStream source) | It constructs a new Scanner that produces values scanned from the specified input stream. |
| Scanner(InputStream source, String charsetName) | It constructs a new Scanner that produces values scanned from the specified input stream. |
| Scanner(Readable source) | It constructs a new Scanner that produces values scanned from the specified source. |
| Scanner(String source) | It constructs a new Scanner that produces values scanned from the specified string. |
| Scanner(ReadableByteChannel source) | It constructs a new Scanner that produces values scanned from the specified channel. |
| Scanner(ReadableByteChannel source, String charsetName) | It constructs a new Scanner that produces values scanned from the specified channel. |
| Scanner(Path source) | It constructs a new Scanner that produces values scanned from the specified file. |
| Scanner(Path source, String charsetName) | It constructs a new Scanner that produces values scanned from the specified file. |
Java Scanner Class Methods
The Java Scanner class offers a variety of methods as outlined below.
| Modifier & Type | Method | Description |
|---|---|---|
void |
close() | It is used to close this scanner. |
| pattern | delimiter() | It is used to get the Pattern which the Scanner class is currently using to match delimiters. |
| Stream<MatchResult> | findAll() | It is used to find a stream of match results that match the provided pattern string. |
| String | findInLine() | It is used to find the next occurrence of a pattern constructed from the specified string, ignoring delimiters. |
| string | findWithinHorizon() | It is used to find the next occurrence of a pattern constructed from the specified string, ignoring delimiters. |
| boolean | hasNext() | It returns true if this scanner has another token in its input. |
| boolean | hasNextBigDecimal() | It is used to check if the next token in this scanner's input can be interpreted as a BigDecimal using the nextBigDecimal() method or not. |
| boolean | hasNextBigInteger() | It is used to check if the next token in this scanner's input can be interpreted as a BigDecimal using the nextBigDecimal() method or not. |
| boolean | hasNextBoolean() | It is used to check if the next token in this scanner's input can be interpreted as a Boolean using the nextBoolean() method or not. |
| boolean | hasNextByte() | It is used to check if the next token in this scanner's input can be interpreted as a Byte using the nextBigDecimal() method or not. |
| boolean | hasNextDouble() | It is used to check if the next token in this scanner's input can be interpreted as a BigDecimal using the nextByte() method or not. |
| boolean | hasNextFloat() | It is used to check if the next token in this scanner's input can be interpreted as a Float using the nextFloat() method or not. |
| boolean | hasNextInt() | It is used to check if the next token in this scanner's input can be interpreted as an int using the nextInt() method or not. |
| boolean | hasNextLine() | It is used to check if there is another line in the input of this scanner or not. |
| boolean | hasNextLong() | It is used to check if the next token in this scanner's input can be interpreted as a Long using the nextLong() method or not. |
| boolean | hasNextShort() | It is used to check if the next token in this scanner's input can be interpreted as a Short using the nextShort() method or not. |
| IOException | ioException() | It is used to get the IOException last thrown by this Scanner's readable. |
| Locale | locale() | It is used to get a Locale of the Scanner class. |
| MatchResult | match() | It is used to get the match result of the last scanning operation performed by this scanner. |
| String | next() | It is used to get the next complete token from the scanner which is in use. |
| BigDecimal | nextBigDecimal() | It scans the next token of the input as a BigDecimal. |
| BigInteger | nextBigInteger() | It scans the next token of the input as a BigInteger. |
| boolean | nextBoolean() | It scans the next token of the input into a boolean value and returns that value. |
byte |
nextByte() | It scans the next token of the input as a byte. |
| double | nextDouble() | It scans the next token of the input as a double. |
| float | nextFloat() | It scans the next token of the input as a float. |
int |
nextInt() | It scans the next token of the input as an Int. |
| String | nextLine() | It is used to get the input string that was skipped by the Scanner object. |
long |
nextLong() | It scans the next token of the input as a long. |
| short | nextShort() | It scans the next token of the input as a short. |
int |
radix() | It is used to get the default radix of the Scanner use. |
void |
remove() | It is used when this implementation of the Iterator does not support the remove operation. |
| Scanner | reset() | It is used to reset the Scanner which is in use. |
| Scanner | skip() | It skips input that matches the specified pattern, ignoring delimiters |
| Stream<String> | tokens() | It is used to get a stream of delimiter-separated tokens from the Scanner object which is in use. |
| String | toString() | It is used to get the string representation of a Scanner. |
| Scanner | useDelimiter() | It is used to set the delimiting pattern of the Scanner which is in use to the specified pattern. |
| Scanner | useLocale() | It is used to sets this scanner's locale object to the specified locale. |
| Scanner | useRadix() | It is used to set the default radix of the Scanner which is in use to the specified radix. |
Example-1
Consider this basic illustration of Java Scanner demonstrating the acquisition of a solitary user input. In this scenario, we are prompting the user to provide a string using the in.nextLine function.
import java.util.*;
public class Main {
public static void main(String args[]){
Scanner in = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = in.nextLine();
System.out.println("Name is: " + name);
in.close();
}
}
Output:
Enter your name: Jack
Name is: Jack
Example-2
import java.util.*;
public class Main {
public static void main(String args[]){
String s = "Hello, Welcome to C# Programming.";
//Create a scanner Object and pass the string into it
Scanner scan = new Scanner(s);
//Check if the scanner has a token
System.out.println("Boolean Result: " + scan.hasNext());
//Print the string
System.out.println("String: " +scan.nextLine());
scan.close();
System.out.println("--------Enter Your Details-------- ");
Scanner in = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = in.next();
System.out.println("Name: " + name);
System.out.print("Enter your age: ");
int i = in.nextInt();
System.out.println("Age: " + i);
System.out.print("Enter your salary: ");
double d = in.nextDouble();
System.out.println("Salary: " + d);
in.close();
}
}
Output:
Boolean Result: true
String: Hello, Welcome to C# Programming.
-------Enter Your Details---------
Enter your name: Andrew
Name: Andrew
Enter your age: 23
Age: 23
Enter your salary: 25000
Salary: 25000.0
Example-3
import java.util.*;
public class Main {
public static void main(String args[]){
String str = "Hello/This is C# Tutorial/My name is Jack.";
//Create scanner with the specified String Object
Scanner scanner = new Scanner(str);
System.out.println("Boolean Result: "+scanner.hasNextBoolean());
//Change the delimiter of this scanner
scanner.useDelimiter("/");
//Printing the tokenized Strings
System.out.println("---Tokenizes String---");
while(scanner.hasNext()){
System.out.println(scanner.next());
}
//Display the new delimiter
System.out.println("Delimiter used: " +scanner.delimiter());
scanner.close();
}
}
Output:
Boolean Result: false
---Tokenizes String---
Hello
This is C# Tutorial
My name is Jack.
Delimiter used: /
Advantages of Scanner Class
- User-Friendly: The Scanner provides a simple and intuitive way to read input, especially for beginners.
- Built-in Parsing: It can directly parse primitive data types (for example, int, double, and boolean) from the input without requiring manual conversion.
- Flexible Input Sources: The scanner can read input from multiple sources like System, in, strings, files, and streams.
- Tokenization Support: It splits input into tokens based on delimiters, which can be customized using useDelimiter.
- Convenient Methods: Provides hasNextXxx methods to validate input types before reading, helping avoid input mismatch exceptions.
- Performance Overhead: Scanner is relatively slower compared to BufferedReader, especially when processing large amounts of data.
- Locale Sensitivity: Parsing numbers depends on the default or set Locale, which may lead to unexpected behaviour in different regions.
- next vs nextLine Confusion: It often confuses beginners since next reads up to space, whereas nextLine reads the full line, causing input skipping issues.
- Limited Formatting Control: The scanner lacks advanced formatting options available in other input methods (like BufferedReader + InputStreamReader).
- Resource Management: Improper use (like closing System.in) can lead to input stream errors in other parts of the application.
- Import Required: Always import java.util.Scanner before using the Scanner class.
- Default Delimiter: Scanner uses whitespace as the default delimiter. Use useDelimiter to change it.
- Primitive Inputs: The scanner can read various primitive types like int, double, float, long, short, byte, and also boolean.
- String Input Differences: next reads only a single word (token). nextLine reads the entire line including spaces.
- Resource Handling: Always close the Scanner using in.close to avoid resource leaks.
- Token Checking: Use hasNext, hasNextInt, hasNextDouble, etc., to check the next token before reading to avoid runtime exceptions.
- Reading a Single Character: Use in.next.charAt(0) to read a single character.
- next reads only a single word (token).
- nextLine reads the entire line including spaces.
Disadvantages of Scanner Class
Important Points to Remember
Conclusion
The Scanner class in Java is a useful tool that enables programs to receive input from various sources such as the keyboard, files, or strings. It plays a crucial role in console-based applications by facilitating the processing of diverse data types like strings, integers, floats, and booleans.
Developers can easily obtain user input using methods like next, nextLine, nextInt, and nextDouble. The Scanner class in Java is valuable for its flexibility in handling delimiters and performing type checking, making it a beneficial tool for programming tasks.
When developing a basic command-line application or handling text data in Java, incorporating the Scanner class facilitates a straightforward and secure approach to receiving input.
Scanner Class MCQs
- Which package contains the Scanner class in Java?
- java.io
- java.lang
- java.util
- java.text
Explanation: The Scanner class is part of the java.util package, and it is commonly used to take input from various sources like input streams, strings, and files.
- What does the Scanner class use as the default delimiter?
- , (comma)
- ; (semicolon)
- Whitespace
- Newline (\n)
Explanation: By default, the Scanner class splits input into tokens based on whitespace characters (spaces, tabs, newlines).
- Which method is used to read an entire line of text input using Scanner?
- next
- readLine
- nextString
- nextLine
Explanation: nextLine reads the entire line including spaces, until the newline character is encountered.
- What does the method next.charAt(0) return?
- The next token as a String
- The first character of the next token
- A character array of the input
- The ASCII code of the first character
Explanation: next returns the next token as a String. Calling charAt(0) on it gives the first character of that token.
- What will happen if you call in.nextInt and the input is not a valid integer?
- It throws NumberFormatException
- It throws an InputMismatchException
- It returns 0
- It skips the input
When the method nextInt is invoked with an input that is not a valid integer, the Scanner class will raise an InputMismatchException.