Scanner is a class. By using the “new” operator, you are creating an object from that class. The parentheses indicate that you are calling a method (in this case, the constructor, which is why its name is same as class. The System.in is the parameter passed to the constructor, in this case telling Scanner where it is scanning from (System.in is the keyboard). So it’s telling the Scanner object to look for input from the keyboard. Basically, this is how you can read something a user types, like answer to a yes/no question, or the number pressed from a numbered menu, etc… Answer from kingtermite on reddit.com
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › util › Scanner.html
Scanner (Java Platform SE 8 )
April 21, 2026 - Java™ Platform Standard Ed. 8 ... A simple text scanner which can parse primitive types and strings using regular expressions.
🌐
W3Schools
w3schools.com › java › java_user_input.asp
Java User Input (Scanner class)
To use the Scanner class, create an object of the class and use any of the available methods found in the Scanner class documentation. In our example, we will use the nextLine() method, which is used to read Strings: import java.util.Scanner; // Import the Scanner class class Main { public static void main(String[] args) { Scanner myObj = new Scanner(System.in); // Create a Scanner object System.out.println("Enter username"); String userName = myObj.nextLine(); // Read user input System.out.println("Username is: " + userName); // Output user input } }
Discussions

What exactly is Scanner??
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns. More on reddit.com
🌐 r/javahelp
22
1
October 31, 2023
import java.util.Scanner;
You will understand with time, in java everything is a class and you are creating an instance of the scanner class and passing System.in as the parameter to its constructor. For now just know when you want the user to input something this is how you do. More on reddit.com
🌐 r/learnprogramming
21
23
December 14, 2025
java - What does Scanner input = new Scanner(System.in) actually mean? - Stack Overflow
Scanner input = new Scanner(System.in); Could you give me a detailed explanation on what the code above is doing step by step? I don't really understand how it works and how it links to me later be... More on stackoverflow.com
🌐 stackoverflow.com
validation - Validating input using java.util.Scanner - Stack Overflow
I'm taking user input from System.in using a java.util.Scanner. I need to validate the input for things like: It must be a non-negative number It must be an alphabetical letter ... etc What's the b... More on stackoverflow.com
🌐 stackoverflow.com
🌐
GeeksforGeeks
geeksforgeeks.org › java › scanner-class-in-java
Scanner Class in Java - GeeksforGeeks
Scanner is a predefined class in Java used to take input from the user. It is present in the java.util package and supports different types of input such as integers, strings, float values, and characters.
Published   May 27, 2026
🌐
Zero To Mastery
zerotomastery.io › blog › java-scanner
Beginner's Guide To Java Scanner (With Code Examples) | Zero To Mastery
Now that Scanner is set up, let’s explore how to read different types of input correctly without running into skipped inputs or crashes. ... The trick is knowing when to use each method, because picking the wrong one can lead to skipped inputs, unexpected results, or program crashes. Let’s go through them one by one. User input often includes single-word responses, full names, or entire sentences. Java provides two different methods for handling this:
🌐
TheServerSide
theserverside.com › blog › Coffee-Talk-Java-News-Stories-and-Opinions › Java-String-input-with-the-Scanner-class
Java Scanner String input example
Interestingly, there is no method for Scanner char input, although there are strategies that can be employed to make that work. But if your program needs to take command-line input from the user in the form of a String, Java’s Scanner class provides all of the methods you will need.
Find elsewhere
🌐
Microsoft Learn
learn.microsoft.com › en-us › dotnet › api › java.util.scanner
Scanner Class (Java.Util) | Microsoft Learn
A simple text scanner which can parse primitive types and strings using regular expressions. [Android.Runtime.Register("java/util/Scanner", DoNotGenerateAcw=true)] public sealed class Scanner : Java.Lang.Object, IDisposable, Java.Interop.IJavaPeerable, Java.IO.ICloseable, Java.Util.IIterator
🌐
Williams College
cs.williams.edu › ~jeannie › cs136 › scanner.pdf pdf
java.util.Scanner CSCI 136: Fall 2009 The Scanner
java.util.Scanner · CSCI 136: Fall 2009 · The Scanner · A Scanner object can parse user input entered on the console or from a file. A Scanner breaks its input · into separate tokens (which are typically separated by white space), and then returns them one at a ·
🌐
YouTube
youtube.com › watch
Java Scanner Tutorial #14 - YouTube
$1,500 OFF ANY Springboard Tech Bootcamps with my code ALEXLEE1500. See if you qualify for the JOB GUARANTEE! 👉 https://bit.ly/3HX970hThis is exactly how yo...
Published   May 9, 2019
🌐
SoftTeco
softteco.com › home › java development › java scanner
Java Scanner: everything you need to know about this Java clas
June 9, 2026 - Scanner is a class in java.util package that is used for parsing primitive types and strings by using regular expressions. Basically it is used for reading input from the command line, although this approach is not very effective for situations ...
🌐
Baeldung
baeldung.com › home › java › java io › java scanner
Java Scanner | Baeldung
January 5, 2024 - In this quick tutorial, we’ll illustrate how to use the Java Scanner class – to read input and find and skip patterns with different delimiters.
Top answer
1 of 6
169

Overview of Scanner.hasNextXXX methods

java.util.Scanner has many hasNextXXX methods that can be used to validate input. Here's a brief overview of all of them:

  • hasNext() - does it have any token at all?
  • hasNextLine() - does it have another line of input?
  • For Java primitives
    • hasNextInt() - does it have a token that can be parsed into an int?
    • Also available are hasNextDouble(), hasNextFloat(), hasNextByte(), hasNextShort(), hasNextLong(), and hasNextBoolean()
    • As bonus, there's also hasNextBigInteger() and hasNextBigDecimal()
    • The integral types also has overloads to specify radix (for e.g. hexadecimal)
  • Regular expression-based
    • hasNext(String pattern)
    • hasNext(Pattern pattern) is the Pattern.compile overload

Scanner is capable of more, enabled by the fact that it's regex-based. One important feature is useDelimiter(String pattern), which lets you define what pattern separates your tokens. There are also find and skip methods that ignores delimiters.

The following discussion will keep the regex as simple as possible, so the focus remains on Scanner.


Example 1: Validating positive ints

Here's a simple example of using hasNextInt() to validate positive int from the input.

Scanner sc = new Scanner(System.in);
int number;
do {
    System.out.println("Please enter a positive number!");
    while (!sc.hasNextInt()) {
        System.out.println("That's not a number!");
        sc.next(); // this is important!
    }
    number = sc.nextInt();
} while (number <= 0);
System.out.println("Thank you! Got " + number);

Here's an example session:

Please enter a positive number!
five
That's not a number!
-3
Please enter a positive number!
5
Thank you! Got 5

Note how much easier Scanner.hasNextInt() is to use compared to the more verbose try/catch Integer.parseInt/NumberFormatException combo. By contract, a Scanner guarantees that if it hasNextInt(), then nextInt() will peacefully give you that int, and will not throw any NumberFormatException/InputMismatchException/NoSuchElementException.

Related questions

  • How to use Scanner to accept only valid int as input
  • How do I keep a scanner from throwing exceptions when the wrong type is entered? (java)

Example 2: Multiple hasNextXXX on the same token

Note that the snippet above contains a sc.next() statement to advance the Scanner until it hasNextInt(). It's important to realize that none of the hasNextXXX methods advance the Scanner past any input! You will find that if you omit this line from the snippet, then it'd go into an infinite loop on an invalid input!

This has two consequences:

  • If you need to skip the "garbage" input that fails your hasNextXXX test, then you need to advance the Scanner one way or another (e.g. next(), nextLine(), skip, etc).
  • If one hasNextXXX test fails, you can still test if it perhaps hasNextYYY!

Here's an example of performing multiple hasNextXXX tests.

Scanner sc = new Scanner(System.in);
while (!sc.hasNext("exit")) {
    System.out.println(
        sc.hasNextInt() ? "(int) " + sc.nextInt() :
        sc.hasNextLong() ? "(long) " + sc.nextLong() :  
        sc.hasNextDouble() ? "(double) " + sc.nextDouble() :
        sc.hasNextBoolean() ? "(boolean) " + sc.nextBoolean() :
        "(String) " + sc.next()
    );
}

Here's an example session:

5
(int) 5
false
(boolean) false
blah
(String) blah
1.1
(double) 1.1
100000000000
(long) 100000000000
exit

Note that the order of the tests matters. If a Scanner hasNextInt(), then it also hasNextLong(), but it's not necessarily true the other way around. More often than not you'd want to do the more specific test before the more general test.


Example 3 : Validating vowels

Scanner has many advanced features supported by regular expressions. Here's an example of using it to validate vowels.

Scanner sc = new Scanner(System.in);
System.out.println("Please enter a vowel, lowercase!");
while (!sc.hasNext("[aeiou]")) {
    System.out.println("That's not a vowel!");
    sc.next();
}
String vowel = sc.next();
System.out.println("Thank you! Got " + vowel);

Here's an example session:

Please enter a vowel, lowercase!
5
That's not a vowel!
z
That's not a vowel!
e
Thank you! Got e

In regex, as a Java string literal, the pattern "[aeiou]" is what is called a "character class"; it matches any of the letters a, e, i, o, u. Note that it's trivial to make the above test case-insensitive: just provide such regex pattern to the Scanner.

API links

  • hasNext(String pattern) - Returns true if the next token matches the pattern constructed from the specified string.
  • java.util.regex.Pattern

Related questions

  • Reading a single char in Java

References

  • Java Tutorials/Essential Classes/Regular Expressions
  • regular-expressions.info/Character Classes

Example 4: Using two Scanner at once

Sometimes you need to scan line-by-line, with multiple tokens on a line. The easiest way to accomplish this is to use two Scanner, where the second Scanner takes the nextLine() from the first Scanner as input. Here's an example:

Scanner sc = new Scanner(System.in);
System.out.println("Give me a bunch of numbers in a line (or 'exit')");
while (!sc.hasNext("exit")) {
    Scanner lineSc = new Scanner(sc.nextLine());
    int sum = 0;
    while (lineSc.hasNextInt()) {
        sum += lineSc.nextInt();
    }
    System.out.println("Sum is " + sum);
}

Here's an example session:

Give me a bunch of numbers in a line (or 'exit')
3 4 5
Sum is 12
10 100 a million dollar
Sum is 110
wait what?
Sum is 0
exit

In addition to Scanner(String) constructor, there's also Scanner(java.io.File) among others.


Summary

  • Scanner provides a rich set of features, such as hasNextXXX methods for validation.
  • Proper usage of hasNextXXX/nextXXX in combination means that a Scanner will NEVER throw an InputMismatchException/NoSuchElementException.
  • Always remember that hasNextXXX does not advance the Scanner past any input.
  • Don't be shy to create multiple Scanner if necessary. Two simple Scanner is often better than one overly complex Scanner.
  • Finally, even if you don't have any plans to use the advanced regex features, do keep in mind which methods are regex-based and which aren't. Any Scanner method that takes a String pattern argument is regex-based.
    • Tip: an easy way to turn any String into a literal pattern is to Pattern.quote it.
2 of 6
9

Here's a minimalist way to do it.

System.out.print("Please enter an integer: ");
while(!scan.hasNextInt()) scan.next();
int demoInt = scan.nextInt();
🌐
Tinocs
java.tinocs.com › lesson › A2 › J.md
The Scanner Class - Tino Intro To Java
January 9, 2026 - In Java, you can get user input via the Scanner class.
🌐
TheServerSide
theserverside.com › blog › Coffee-Talk-Java-News-Stories-and-Opinions › Java-Scanner-User-Input-example-String-next-int-long-char
Java Scanner User Input Example
This tutorial on how to use the Java Scanner for user input will quickly show you how to import java.util, take String, int, double and char input, and teach you the difference between the ...
🌐
Medium
medium.com › buzz-code › java-8-scanner-class-660b03d4bb91
Java 8 | Scanner Class
January 18, 2021 - Java 8 | Scanner Class Scanner Class — One of the java.util.package that gets user input. Hi guys! So until the last time we’ve been practicing the two dimensional array. Today we’re gonna …
🌐
MC Seed Map
mcseedmap.net
Seed Map Viewer and Seed Finder for Minecraft
For Java Edition: while playing, press T to open the chat, type "/seed" without the quotes, and press ENTER.
🌐
Oracle
docs.oracle.com › en › java › javase › 17 › docs › api › java.base › java › util › Scanner.html
Scanner (Java SE 17 & JDK 17)
April 21, 2026 - A simple text scanner which can parse primitive types and strings using regular expressions.