For working professionals
For fresh graduates
More
Step by Step Java Tutorial Con…
1. Introduction to Java
2. What is Java?
3. History of Java
4. Java Tutorial for Beginners
5. How Do Java Programs Work?
6. JDK in Java
7. C++ Vs Java
8. Java vs. Python
9. Java vs. JavaScript
10. From Java Source Code to Executable
11. How to Install Java in Linux
12. How to Install Java in Windows 10
13. Java Hello World Program
14. Structure of Java Program and Java Syntax
15. Operators in Java
16. Java If-else
17. Switch Case In Java
18. Loops in Java
19. Infinite loop in Java
20. For Loop in Java
21. For Each Loop in Java
22. Constructor in Java
23. Constructor Overloading in Java
24. Copy Constructor in Java
25. Default Constructor in Java
26. Parameterized Constructors in Java
27. Constructor Chaining In Java
28. Finalize Method in Java
29. Static Method in Java
30. Equals Method in Java
31. Abstract Method in Java
32. toString() Method in Java
33. Difference between equals method in Java
34. Inheritance in Java
35. Multiple Inheritance in Java
36. Hierarchical Inheritance in Java
37. Java Classes and Objects
38. Scanner Class in java
Now Reading
39. All classes in java are inherited from which class
40. What is Nested Class in Java
41. POJO Class in Java
42. Anonymous Class in Java
43. Final Class in Java
44. Object Class in Java
45. Packages in Java
46. Access Modifiers in Java
47. Static Keyword In Java
48. Final Keyword in Java
49. Checked and Unchecked Exceptions in Java
50. User Defined Exception in Java
51. Error vs. Exception in Java
52. Java Collection
53. Collections in Java
54. Garbage Collection in Java
55. Generics In Java
56. Java Interfaces
57. Functional Interface in Java
58. Marker Interface in Java
59. Streams in Java
60. Byte stream in java
61. File Handling in Java
62. Thread in Java
63. Thread Lifecycle In Java
64. Daemon Thread in Java
65. Thread Priority in Java
66. Deadlock in Java
67. String Pool in Java
68. Java Database Connectivity(JDBC)
69. Design Patterns in Java
70. Functional Programming in Java
71. OOP vs Functional vs Procedural
72. Heap Memory and Stack Memory in Java
73. Applet in Java
74. Java Swing
75. Java Frameworks
76. Hibernate Framework
77. JUnit Testing
78. How to Install Eclipse IDE for Java?
79. Command line arguments in Java
80. Jar file in Java
81. Java Clean Code
82. OOPs Concepts in Java
83. Java OOPs Concepts
84. Overloading vs Overriding in Java
85. Java 8 features
86. String in Java
87. String to int in Java
88. Why String Is Immutable in Java?
89. Primitive Data Types in Java
90. Non-Primitive Data Types in Java
91. This and Super Keyword in Java
92. HashMap in Java
93. Comparable And Comparator in Java
94. Type Casting in Java
95. Arrays Sort in Java with Examples
96. Variable Hiding and Variable Shadowing in Java
97. Enum in Java
98. Substring in Java
99. Pattern Programs in Java
100. Hashcode in Java
101. What is ByteCode in Java?
102. How To Take Input From User in Java
103. GCD of Two Numbers in Java
104. Linked List in Java
105. Arithmetic Operators in Java
106. Conditional Operators in Java
107. Stack and Queue in Java
108. Array Length in Java
109. Number Pattern Program in Java
110. Split in java
111. Map In Java
112. Difference Between Throw and Throws in Java
113. Difference Between Data Hiding and Abstraction
114. HashSet in Java
115. String Length in Java
116. Factorial Using Recursion in Java
117. DateFormat in Java
118. StringBuilder Class in java
119. Instance variables in Java
120. Java List Size
121. Java APIs
122. Reverse an Array in Java
123. StringBuffer and StringBuilder Difference in Java
124. Java Program to Add Two Numbers
125. String to Array in Java
126. Regular Expressions in Java
127. Identifiers in Java
128. Data Structures in Java
129. Set in Java
130. Pass By Value and Call By Reference in Java
131. Try Catch in Java
132. Bubble Sort in Java
133. Caesar Cipher Program in Java
134. Queue in Java
135. Object Creation in Java
136. Multidimensional Array in Java
137. How to Read a File in Java
138. String Comparison in Java
139. Volatile Keyword in Java
140. Control Statements in Java
141. Jagged Array in Java
142. Two-Dimensional Array in Java
143. Java String Format
144. Replace in Java
145. charAt() in Java
146. CompareTo in Java
147. Matrix Multiplication in Java
148. Static Variable in Java
149. Event Handling in Java
150. parseInt in Java
151. Java ArrayList forEach
152. Abstraction in Java
153. String Input in Java
154. Logical Operators in Java
155. instanceof in Java
156. Math Floor in Java
157. Selection Sort Java
158. int to char in Java
159. Stringtokenizer in java
160. Implementing and Manipulating Abs in Java
161. Char array to string in java
162. Convert Double To String In Java
163. Deque in Java
164. Converting a List to an Array in Java
165. The Max function in java
166. Removing whitespace from string in java
167. String arrays in Java
168. Strings in Java Vs Strings in Cpp
169. Sum of digits of a number in Java
170. Art of Graphical User Interfaces
171. Trim in Java
172. RxJava
173. Recursion in Java
174. HashSet Java
175. Difference Between Java and Python
176. Square Root in Java
177. Reverse A String in Java
178. Even Odd Program in Java
179. Fibonacci Series in Java
180. Prime Number Program in Java
181. Java Program to Print Prime Numbers in a Given Range
182. Java Leap Year Program
183. Swapping of Two Numbers in Java
184. LCM of Two Numbers in Java
185. Math.sqrt() Function in Java
186. Area of Triangle in Java
187. Sort a String In Java
188. Factorial Program in Java
189. Javafx
190. Lambda expression in java
191. Setup Java Home and IDE on macOS
Scanner class is one of the most talked about topics in Java. It is located in the java.util package and is used to obtain the user input. If you are a programming enthusiast, here is a tutorial on scanner class in Java!
This tutorial discusses Java scanners, Java scanner class constructors, Java scanner class methods, and much more. Read on to learn more about the scanner class in Java!
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;
public class ScannerExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter an integer: ");
int num = scanner.nextInt();
System.out.println("You entered: " + num);
System.out.print("Enter a line of text: ");
scanner.nextLine();
String str = scanner.nextLine();
System.out.println("You entered: " + str);
scanner.close();
}
}
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!". It also allows you to read its contents using the 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:
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 there is another token 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);
}
40. 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");
}
Scanner class in Java is as important as the other concepts in Java. You can take up courses curated by online learning platforms like upGrad if you want a firmer grasp of the subject. Hopefully, this tutorial will be helpful to students who want to learn Java.
1. What types of inputs can the scanner read?
The scanner class reads inputs of several types. These are as follows:
2. What is the difference between the Scanner class's next() and nextLine() methods in Java?
The next() method reads the next token from the input stream. But the nextLine() method reads the next line. This is their fundamental difference.
3. Can the Scanner class read input from a file?
Yes, you can use the scanner class to read input from a file in Java. You can do this by supplying the file path as a parameter to the scanner class's constructor.
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
+918045604032
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.