For working professionals
For fresh graduates
More
6. JDK in Java
7. C++ Vs Java
16. Java If-else
18. Loops in Java
20. For Loop in Java
45. Packages in Java
52. Java Collection
55. Generics In Java
56. Java Interfaces
59. Streams in Java
62. Thread in Java
66. Deadlock in Java
73. Applet in Java
74. Java Swing
75. Java Frameworks
77. JUnit Testing
80. Jar file in Java
81. Java Clean Code
85. Java 8 features
86. String in Java
92. HashMap in Java
97. Enum in Java
100. Hashcode in Java
104. Linked List in Java
108. Array Length in Java
110. Split in java
111. Map In Java
114. HashSet in Java
117. DateFormat in Java
120. Java List Size
121. Java APIs
127. Identifiers in Java
129. Set in Java
131. Try Catch in Java
132. Bubble Sort in Java
134. Queue in Java
141. Jagged Array in Java
143. Java String Format
144. Replace in Java
145. charAt() in Java
146. CompareTo in Java
150. parseInt in Java
152. Abstraction in Java
153. String Input in Java
155. instanceof in Java
156. Math Floor in Java
157. Selection Sort Java
158. int to char in Java
163. Deque in Java
171. Trim in Java
172. RxJava
173. Recursion in Java
174. HashSet Java
176. Square Root in Java
189. Javafx
Let’s say you’re building a program that asks users to enter their name, age, or favorite color. How do you get that input from the keyboard? That’s where the Scanner class in Java comes in handy. It allows you to read input from various sources—like the keyboard, files, or strings—making your programs interactive and user-friendly.
In Java, Scanner is a utility class found in the java.util package. It's commonly used to read input from the console and supports different data types like int, double, String, and more. Scanner helps bridge the gap between user input and your program’s logic, whether you're building a calculator, form-based application, or game.
In this blog, we’ll explore everything you need to know about the Scanner class in Java—its syntax and common methods. Let’s get started!
Combine your Java expertise with professional software engineering skills. Join Upgrad’s Software Engineering course and develop a strong foundation in building high-quality software.
The "scanner" class in Java reads input from various sources, such as the terminal, files, and strings. To use the Scanner class, first, declare an instance of it.
Learn how to declare a scanner object through this example:
import java.util.Scanner; // Importing the Scanner class to take input from the user
public class ScannerExample {
public static void main(String[] args) {
// Creating a Scanner object to read input from the keyboard (System.in)
Scanner scanner = new Scanner(System.in);
// Prompting the user to enter an integer
System.out.print("Enter an integer: ");
int num = scanner.nextInt(); // Reading an integer input from the user
System.out.println("You entered: " + num); // Printing the entered integer
// Prompting the user to enter a line of text
System.out.print("Enter a line of text: ");
scanner.nextLine(); // This line is needed to consume the leftover newline character after nextInt()
String str = scanner.nextLine(); // Reading the actual line of text from the user
System.out.println("You entered: " + str); // Printing the entered text
scanner.close(); // Closing the Scanner object to free up resources
}
}
Output
Enter an integer: 10
You entered: 10
Enter a line of text: Hi, I'm learning scanner class in JAVA!
You entered: Hi, I'm learning scanner class in JAVA!
In Java, you can create a scanner object to read input from various sources. These sources are the console, files, or strings. To specify the source of input, you pass an appropriate input stream or source to the scanner constructor.
For instance, if you want to read input from the console, you can create a scanner object. Then pass the “System.in” input stream to its constructor like this:
Scanner scanner = new Scanner(System.in);
This creates a scanner object named scanner that reads input from the console.
On the other hand, if you want to read input from a string, you can create a scanner object and then pass the string to its constructor like this:
Scanner scanner = new Scanner("Hello, UpGrad!");
This creates a scanner object that parses the string "Hello, UpGrad!" and allows you to read its contents using Scanner methods such as “next(),” “nextInt(),” or “nextLine().”
You can also create a scanner object to read input from a file or any other input stream. In this case, you would pass the file or stream to the scanner constructor instead of “System.in” or a string.
The scanner class provides several constructors. They allow you to create a scanner object to read input from different sources.
Here are the primary constructors the scanner class provides:
Constructor | Description |
Scanner(File source) | Creates a scanner to read input from a file. |
Scanner(InputStream source) | Reads input from a byte stream (e.g., System.in). |
Scanner(String source) | Reads input from a given string. |
Scanner(Readable source) | Reads input from a character stream. |
Scanner(Path source) | Reads input from a file specified by a Path object. |
Scanner(File source, String charsetName) | Reads input from a file using a specified character encoding. |
Scanner(InputStream source, String charsetName) | Reads input from a byte stream using a specific character set. |
Scanner(ReadableByteChannel source) | Reads input from a byte channel. |
Scanner(ReadableByteChannel source, String charsetName) | Reads input from a byte channel using a specified character set. |
Scanner(Path source, String charsetName) | Reads input from a file (via Path) using the specified character encoding. |
Take your Java skills to new heights. Enroll in the Executive Diploma in Data Science & AI with IIIT-B and expand your expertise.
Here is a list of scanner class methods in Java
1. close() - Closes the scanner object and frees any associated system resources.
Scanner scanner = new Scanner(System.in);
scanner.close();
2. hasNext() - Returns true if another token is in the input.
Scanner scanner = new Scanner(System.in);
if (scanner.hasNext()) {
String input = scanner.next();
System.out.println("Input: " + input);
}
3. hasNextLine() - Returns true if there is another line in the input.
Scanner scanner = new Scanner("Hello,\nworld!");
if (scanner.hasNextLine()) {
System.out.println("Found next line: " + scanner.nextLine()); // Output: Found next line: Hello,
}
4. next() - Returns the next token in the input as a string.
Scanner scanner = new Scanner("Hello, world!");
String word = scanner.next();
System.out.println(word); // Output: Hello,
5. useLocale(Locale locale): Sets the scanner's locale to the specified locale.
Scanner scanner = new Scanner("1.234,56");
scanner.useLocale(Locale.GERMAN);
double num = scanner.nextDouble(); // num = 1234.56
6. useRadix(int radix): Sets the scanner's radix to the specified radix.
Scanner scanner = new Scanner("FF");
scanner.useRadix(16);
int num = scanner.nextInt(); // num = 255
7. findAll(Pattern pattern): Returns a stream of match results that match the specified regular expression pattern.
Scanner scanner = new Scanner("Hello, World!");
Pattern pattern = Pattern.compile("\\w+");
scanner.findAll(pattern).forEach(matchResult -> System.out.println(matchResult.group()));
// Output: Hello World
8. nextLine() in Java - Returns the next line of input as a string.
Scanner scanner = new Scanner("Hello,\nworld!");
String line = scanner.nextLine();
System.out.println(line); // Output: Hello,
9. nextDouble() - Returns the next token in the input as a double.
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a double value: ");
double input = scanner.nextDouble();
System.out.println("Input value: " + input);
10. nextBoolean() - Returns the next token in the input as a boolean.
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a boolean value (true/false): ");
boolean input = scanner.nextBoolean();
System.out.println("Input value: " + input);
11. nextByte() - Returns the next token in the input as a byte.
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a byte value: ");
byte input = scanner.nextByte();
System.out.println("Input value: " + input);
12. nextShort() - Returns the next token in the input as a short.
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a short value: ");
short num = scanner.nextShort();
System.out.println("The entered short value is " + num);
13. nextLong() - Returns the next token in the input as a long.
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a long value: ");
long num = scanner.nextLong();
System.out.println("The entered long value is " + num);
14. nextFloat() - Returns the next token in the input as a float.
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a float value: ");
float input = scanner.nextFloat();
System.out.println("Input value: " + input);
15. useDelimiter() - Sets the delimiter for parsing input.
Scanner scanner = new Scanner("Hello,world!");
scanner.useDelimiter(",");
System.out.println(scanner.next()); // Output: Hello
System.out.println(scanner.next()); // Output: world!
16. skip() - Skips input that matches the specified pattern.
Scanner scanner = new Scanner("1,2,3,4,5");
scanner.useDelimiter(",");
while (scanner.hasNext()) {
if (scanner.hasNextInt()) {
int num = scanner.nextInt();
System.out.println(num);
} else {
scanner.skip(",");
}
}
17. findInLine() - Searches for the next occurrence of the specified pattern in the current input line.
Scanner scanner = new Scanner("Hello, 123, world!");
String match = scanner.findInLine("\\d+");
System.out.println(match); // Output: 123
Scanner scanner = new Scanner("The quick brown fox jumps over the lazy dog.");
String result = scanner.findInLine("fox");
System.out.println(result); // Output: fox
18. findWithinHorizon(String pattern, int horizon) - Searches for the next occurrence of the specified pattern in the input up to the specified horizon.
Scanner scanner = new Scanner("abc123def456");
System.out.println(scanner.findWithinHorizon("\\d+", 3));
// Output: null (pattern not found within horizon of 3 characters)
19. hasNextByte(): Returns true if the scanner has another token that is a byte.
Scanner scanner = new Scanner(System.in);
if (scanner.hasNextByte()) {
byte b = scanner.nextByte();
System.out.println("Byte: " + b);
}
20. match() - Returns the MatchResult for the last match operation.
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String input = scanner.next();
scanner.useDelimiter("[aeiou]");
scanner.next();
MatchResult result = scanner.match();
System.out.println("Last match: " + result.group());
21. ioException() - Returns the IOException last thrown by the scanner's underlying Readable.
Scanner scanner = new Scanner(new java.io.FileReader("nonexistent.txt"));
try {
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
} catch (java.util.NoSuchElementException e) {
if (scanner.ioException() == null) {
System.out.println("Scanner is still valid, but there is no more input");
} else {
System.out.println("Scanner is invalid due to an IOException: " + scanner.ioException().getMessage());
}
}
// Output: Scanner is invalid due to an IOException: null (file not found)
22. delimiter() - Returns the current delimiter pattern as a string.
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string with multiple words: ");
String input = scanner.nextLine();
scanner.useDelimiter("\\s");
while (scanner.hasNext()) {
System.out.println("Word: " + scanner.next());
}
23. locale() - Returns the locale associated with the scanner.
Scanner scanner = new Scanner("one deux trois");
scanner.useLocale(Locale.FRENCH);
while (scanner.hasNext()) {
System.out.println(scanner.next());
}
// Output: one
// deux
// trois
System.out.println(scanner.locale());
// Output: fr_FR
24. radix() - Returns the default radix for parsing integers.
Scanner scanner = new Scanner(System.in);
scanner.useRadix(16);
System.out.println("Enter a hexadecimal number: ");
int num = scanner.nextInt();
System.out.println("The entered hexadecimal number is " + num);
25. reset() - Resets the scanner to its initial state.
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string with multiple words: ");
String input = scanner.nextLine();
scanner.useDelimiter("\\s");
while (scanner.hasNext()) {
System.out.println("Word: " + scanner.next());
}
scanner.reset();
System.out.println("Original delimiter: " + scanner.delimiter());
26. toString() - Returns a string representation of the scanner object.
Scanner scanner = new Scanner("hello world");
System.out.println(scanner.toString());
27. tokens() - Returns an Iterator over the tokens in the input.
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string with multiple words: ");
String input = scanner.nextLine();
scanner.useDelimiter("\\s");
Iterator<String> tokens = scanner.tokens();
while (tokens.hasNext()) {
System.out.println("Token: " + tokens.next());
}
28. remove() - Removes the current token from the input.
Scanner scanner = new Scanner("apple orange banana");
while (scanner.hasNext()) {
String fruit = scanner.next();
System.out.println(fruit);
if (fruit.equals("orange")) {
scanner.remove();
System.out.println("Removed " + fruit);
}
}
29. hasNextBigDecimal() - Returns true if there is another token in the input, and it can be interpreted as a BigDecimal.
Scanner scanner = new Scanner(System.in);
if (scanner.hasNextBigDecimal()) {
BigDecimal decimal = scanner.nextBigDecimal();
System.out.println("Decimal: " + decimal);
}
30. nextBigDecimal() - Returns the next token in the input as a BigDecimal.
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a BigDecimal value: ");
BigDecimal input = scanner.nextBigDecimal();
System.out.println("Input value: " + input);
31. hasNextBigInteger() - Returns true if there is another token in the input, and it can be interpreted as a BigInteger.
Scanner scanner = new Scanner(System.in);
if (scanner.hasNextBigInteger()) {
BigInteger integer = scanner.nextBigInteger();
System.out.println("Integer: " + integer);
}
32. nextBigInteger() - Returns the next token in the input as a BigInteger.
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a BigInteger value: ");
BigInteger input = scanner.nextBigInteger();
System.out.println("Input value: " + input);
33. hasNextBoolean() - Returns true if the scanner has another boolean token.
Scanner scanner = new Scanner(System.in);
if (scanner.hasNextBoolean()) {
boolean bool = scanner.nextBoolean();
System.out.println("Boolean: " + bool);
}
34. hasNextPattern() - Returns true if the next token in the input matches the specified pattern.
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = scanner.next();
if (scanner.hasNextPattern("\\d+")) {
int num = scanner.nextInt();
System.out.println("The entered string is: " + str + " and the number is: " + num);
} else {
System.out.println("The entered string is: " + str);
}
35. nextInt() in Java- Returns the next token in the input as an int.
Scanner scanner = new Scanner(System.in);
System.out.println("Enter an integer: ");
int num = scanner.nextInt();
System.out.println("The entered integer is " + num);
36. hasNextDouble() - Returns true if there is another token in the input, and it can be interpreted as a double.
Scanner scanner = new Scanner(System.in);
if (scanner.hasNextDouble()) {
double d = scanner.nextDouble();
System.out.println("Double: " + d);
}
37. hasNextFloat() - Returns true if another token is in the input and can be interpreted as a float.
Scanner scanner = new Scanner(System.in);
if (scanner.hasNextFloat()) {
float f = scanner.nextFloat();
System.out.println("Float: " + f);
}
38. hasNextInt() - Returns true if there is another token in the input, and it can be interpreted as an int.
Scanner scanner = new Scanner(System.in);
if (scanner.hasNextInt()) {
int i = scanner.nextInt();
System.out.println("Int: " + i);
}
39. hasNextLong() - Returns true if another token is in the input and can be interpreted as a long.
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a long value: ");
if (scanner.hasNextLong()) {
long value = scanner.nextLong();
System.out.println("You entered: " + value);
} else {
System.out.println("Invalid input");
}
The Scanner class in Java simplifies user input by providing easy methods to read data from various sources like keyboard, files, or strings. Its flexibility and built-in parsing capabilities make it ideal for beginners and professionals alike. You can efficiently handle input operations in Java-based applications and programs by understanding its constructors and usage.
The Scanner class is used to read input from various sources such as keyboard, files, strings, or byte streams. It provides methods to parse primitive types like int, double, and boolean, making it easier to handle user input or file data.
The Scanner class is part of the java.util package. You need to import it using import java.util.Scanner; at the beginning of your program to use it.
You can create it using:
Scanner sc = new Scanner(System.in);
This allows the program to read user input from the console.
Scanner provides methods like nextInt(), nextDouble(), nextBoolean(), nextLine(), next(), and nextFloat() to read specific data types directly from the input source.
next() reads input until a space is encountered, while nextLine() reads the entire line, including spaces, until a newline character is found. Use nextLine() when you want to capture full-line input.
You can use:
Scanner sc = new Scanner(new File("filename.txt"));
This allows you to read file contents line by line or token by token using Scanner methods.
A java.util.InputMismatchException is thrown. For example, if you use nextInt() and enter a string, the program crashes. Always validate input or use hasNextInt() before reading.
Use an extra nextLine() after methods like nextInt() to consume the leftover newline character in the input buffer before reading the full line.
Yes. You can use:
Scanner sc = new Scanner("Some text");
or
Scanner sc = new Scanner(Paths.get("file.txt"));
to read input from a string or a file path, respectively.
Yes, especially when reading from files or input streams. Closing the Scanner releases system resources. Use sc.close(); at the end. But avoid closing it if it's tied to System.in to prevent losing console input.
No, the Scanner class is not thread-safe. If you’re using it in a multi-threaded environment, you should synchronize access or use thread-safe alternatives like BufferedReader with proper locking mechanisms.
Take the Free Quiz on Java
Answer quick questions and assess your Java knowledge
Author
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918068792934
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.