Reading Basic Data Types With Scanner Methods
The Scanner class, in package java.util, was introduced to make reading basic data types from a character input source easier in Java.
Predicting Where Each Scanner Reads From
Before any explanation of how input works in Java, look at a short piece of code. It creates two Scanner objects, and each one is built from a different kind of argument. Your job is to decide what each Scanner will be reading characters from. Make your guess first, then compare it with the explanation that follows.
What do you think happens?
What is each Scanner reading characters from?
Reveal answer
first reads standard input, and second reads the text 7 11
The argument passed to the constructor selects the source. System.in names standard input, which in a typical console run is the keyboard. A String argument is a source in its own right, so the second Scanner reads the characters of the text 7 11 from beginning to end.
Why Java Needed the Scanner Class
Many beginning Java programs need input from a user, and the first question is usually how to get that input into the program at all. Java's built-in support for basic input has long been considered thin, or at least dependent on fairly advanced techniques. A beginner who only wants to read a whole number or a decimal value from the console would have to work with lower-level pieces before the program could do anything useful.
The Scanner class was added to make reading basic data types from a character input source easier. Its purpose is narrow and practical: take characters from a source and make the basic data types in those characters easier to read. It is not a complete solution to every input problem, but it is a substantial improvement for everyday use. The class belongs to the package java.util, which is why programs that use it need to make that package available to the compiler.
A Scanner Wraps a Source
The key idea is that a Scanner does not own the characters it reads. It is a wrapper around an input source. The source is chosen by the constructor: whatever you pass inside the parentheses when you write new Scanner is the place the Scanner will draw characters from. Once that connection exists, the Scanner offers its input routines.
In that general form, source is a placeholder for one of the permitted kinds of input. The word name is simply the variable that will hold the Scanner object. The important part is the argument, because it decides what the Scanner is connected to.
The constructor accepts several kinds of input source. The source text names four of them directly: a Reader, an InputStream, a String, and a File. The text also notes that other possibilities exist beyond these four, so treat that list as the set the source explicitly names rather than a complete catalog. The three sources that matter most for this article are described in the subsections below.
Tracing Characters From Source to Scanner
Follow the path characters take. A character source, whether standard input, a Reader, or a String, supplies characters. Those characters flow into the Scanner, which sits between the source and your program. The Scanner does not store its own copy of the source as a separate thing you must manage; it is attached to the source chosen in the constructor and reads from there. Your program then calls the Scanner's input methods and receives values through the Scanner.
Read the diagram from left to right in terms of responsibility. The three sources on the left are where characters originate. Whichever one you chose in the constructor is the only one that feeds this particular Scanner. The Scanner sits in the middle as the connection point, and your program sits on the right, where it uses the Scanner's methods to get values. Changing the argument to the constructor changes the left side of the picture and nothing else.
Comparing the Three Constructor Sources
The three sources differ in what they contain and where the characters come from. The table below puts them side by side using only what the source text says about each one.
| Constructor argument | Where characters come from | Typical use in this course |
|---|---|---|
| System.in | Standard input, the keyboard in a typical console run | The most common case in introductory programs |
| A Reader variable such as charSource | A character source of type Reader that already exists | When you already hold a Reader |
| A String such as "7 11" | The text itself, read from beginning to end | Reading characters that are already in the program as text |
Three constructor sources for a Scanner
Worked Example: Tracing a Scanner Built From a String
Following the characters of a String source
A program creates a Scanner from the String "7 11". Trace where the Scanner's characters come from and in what order they are processed.
- 1Identify the argument
The constructor argument is the String "7 11". That argument selects the source, so the Scanner is wrapped around this text.
- 2Recognize the source kind
A String is one of the permitted source kinds named in the source text. Nothing is read from the keyboard, because the keyboard is not the source.
- 3Trace the order
The String source is read from beginning to end, in the same way a stream of those characters would be processed. The Scanner works through the characters 7, a space, 1, and 1 in that order.
- 4Connect to the program
The Scanner is the connection point, and the program gets values from it through the Scanner's instance methods. Those methods are covered in later sections of the course.
The Scanner reads the characters of the text 7 11 from start to finish, and its source is that String rather than the keyboard.
Mistakes When Creating a Scanner
The mistakes below come up often when learners first create Scanner objects. Each one comes from misreading how the constructor and the source relate.
Common mistake Calling input methods on the class name instead of an object
What it looks likeScanner.nextLine() written without first creating a Scanner
Why it failsThe input routines are instance methods, so they belong to a Scanner object rather than to the class.
Do this insteadCreate the object first, such as Scanner keyboardInput = new Scanner(System.in), and then call the method on keyboardInput.
Common mistake Believing the Scanner owns the characters it reads
Why it failsA Scanner is a wrapper around an input source. It does not own the characters, and the source is what the constructor selects.
Do this insteadThink of the Scanner as a connection. Look at the constructor argument to find out where the characters come from.
Common mistake Expecting a String source to wait for keyboard typing
What it looks likeCreating new Scanner("7 11") and waiting for the user to type numbers
Why it failsA String source is read from beginning to end, and the text is already part of the constructor call.
Do this insteadUse System.in when you want input typed by the user, and use a String when the text is already known to the program.
Common mistake Assuming the four named sources are the only ones
Why it failsThe source text names a Reader, an
InputStream, a String, and a File, and it notes that other possibilities exist.Do this insteadTreat the four named kinds as the set the source explicitly describes, and check documentation for any other source type you meet.
Practice: Naming the Source
For each line below, state which kind of source the Scanner reads from: standard input, a Reader variable, or a String. Then explain in one sentence what the constructor argument tells you. Lines: (a) Scanner a = new Scanner(System.in); (b) Scanner b = new Scanner(charSource); (c) Scanner c = new Scanner("hello there");
Hints
- Look only at the text inside the parentheses of each constructor call.
System.innames standard input, and a bare variable name holding a Reader is a Reader source.- Text inside double quotes is a String source, read from beginning to end.
Key Takeaways
- The Scanner class, in package
java.util, was added to make reading basic data types from a character input source easier in Java. - A Scanner is a wrapper around an input source, and the constructor argument selects that source, such as
System.in, a Reader, or a String. - The input routines of a Scanner are instance methods, so you must create a Scanner object before you can call them.
- A String source is read from beginning to end, so it supplies text that is already in the program rather than waiting for keyboard input.