Last Updated: 28 May, 2022
The Scanner is a Java class and it is available in java.util
package.
The Scanner class is used to get the input in the Java program from the different sources, the source may be standard input (input from keyboard), files, etc.
To use the Scanner class, we need to create an object of the Scanner class If we are taking standard input we need to pass System.in
as a parameter. We may pass an object of class File if we want to read input from a file.
The Scanner object breaks its input into tokens using a delimiter pattern, the default delimiter is whitespace.
Scanner class declaration
public final class Scanner
extends Object
implements Iterator<String>, Closeable
Method | Description |
---|---|
String next() | It reads the next complete token from the invoking scanner. |
String next(Pattern pattern) | It reads the next token if it matches the specified pattern. |
String next(String pattern) | It reads the next token if it matches the pattern constructed from the specified string. |
boolean nextBoolean() | It reads a boolean value from the user. |
byte nextByte() | It reads a byte value from the user. |
double nextDouble() | It reads a double value from the user. |
float nextFloat() | It reads a floating-point value from the user. |
int nextInt() | It reads an integer value from the user. |
long nextLong() | It reads a long value from the user. |
short nextShort() | It reads a short value from the user. |
String nextLine() | It reads a string value from the user. |
boolean hasNext() | It returns true if the invoking scanner has another token in its input. |
void remove() | It is used when remove operation is not supported by this implementation of Iterator. |
void close() | It closes the invoking scanner. |
Example: Taking input from user using Scanner Class
Output
Enter Student Information
Enter Student Name: Virat
Enter Student Marks: 420
Enter Marks Percentage: 86.60
Is Pass: true
-------------------------------
Student Examination Result
-------------------------------
Student Name Virat Pass the Examination with Total Marks 420 and Percentage (%): 86.6
Remarks: PASS
That's all guys, hope this Java article is helpful for you.
Happy Learning... 😀
feedback@javabytechie.com