Scanners

Which of the Following Statements Correctly Creates a Scanner Object for Keyboard Input?

If you have ever taken a Java programming course, you have likely encountered a question about which of the statements creates a scanner object for keyboard input. It sounds simple, but understanding the correct syntax — and why each alternative fails — is foundational to writing effective console-based Java applications. Whether you are a student debugging your first program or a developer revisiting the basics, this guide breaks down every aspect of the Scanner class, keyboard input handling, and the common mistakes that trip up beginners.

Java's Scanner class, found in the java.util package, is the standard tool for reading input from a variety of sources, including keyboard input via System.in. Knowing which Scanner class method reads an int and how to instantiate the class correctly are both critical skills. Just as important is understanding what happens when resources are not properly managed — something we cover in our guide on resource leak: Scanner is never closed.

What Is the Scanner Class in Java?

The Scanner class is part of the java.util package and was introduced in Java 5. It provides a simple interface for parsing primitive types and strings from various input streams. For most beginner programs, the stream in question is the keyboard — represented in Java as System.in.

What is a scanner object?
What is a scanner object?

Think of a Scanner object as a wrapper. Raw byte streams coming from the keyboard are difficult to work with directly. The Scanner wraps that raw stream and exposes convenient methods like nextLine(), nextInt(), and nextDouble(), making it easy to read structured input without manually parsing bytes.

According to the Oracle Java documentation, Scanner uses a delimiter pattern — by default any whitespace — to break its input into tokens. This behavior is important to understand when reading multiple values on the same line.

Importing the Scanner Class

Before you can create a Scanner object, you must import the class at the top of your Java file. The import statement is:

import java.util.Scanner;

Forgetting this import is one of the most common causes of compilation errors in beginner Java programs. Without it, the compiler does not know what Scanner refers to, and it will throw an error like cannot find symbol.

Alternatively, you can use a wildcard import:

import java.util.*;

While this imports all classes from the java.util package, it is generally better practice to import only what you need to keep your code readable and avoid namespace conflicts.

Input Sources Supported by Scanner

Although we focus on keyboard input in this article, it is worth knowing that Scanner is flexible. It can read from:

  • Standard input (System.in) — keyboard input in console applications
  • Files — using a File or Path object
  • Strings — parsing an in-memory string as if it were a stream
  • Input streams — any InputStream or Readable

This versatility is one reason Scanner remains a staple in Java education and production code alike. You can also explore whether a scanner is an input or output device in the physical hardware sense, which makes for an interesting contrast with its software counterpart.

Which Statement Correctly Creates a Scanner Object for Keyboard Input?

This is the central question. When an exam or assignment asks you to identify which of the following statements creates a scanner object for keyboard input, the answer is always the same — the statement that passes System.in as the argument to the Scanner constructor.

The Correct Syntax Explained

The correct statement is:

Scanner keyboard = new Scanner(System.in);

Let us break this down piece by piece:

  • Scanner — the data type (class) of the variable
  • keyboard — the variable name (any valid identifier works; sc, input, and scanner are also common)
  • new Scanner(...) — invokes the constructor to create a new instance
  • System.in — the standard input stream, connected to the keyboard by default

The variable name does not affect functionality. Scanner sc = new Scanner(System.in); works exactly the same as Scanner keyboard = new Scanner(System.in);. What matters is the argument passed to the constructor: it must be System.in for keyboard input.

Common Wrong Answers and Why They Fail

Multiple-choice questions on this topic typically include several plausible-looking alternatives. Here is what goes wrong with each:

Statement Problem
Scanner keyboard = new Scanner(); No argument — Scanner has no zero-argument constructor. Compile error.
Scanner keyboard = Scanner(System.in); Missing new keyword. Java cannot instantiate objects without new.
Scanner keyboard = new Scanner(System.out); System.out is a PrintStream (output), not an input source. Compiles but reads nothing meaningful.
scanner keyboard = new scanner(System.in); Java is case-sensitive. scanner (lowercase) is not a recognized class.
Scanner keyboard = new Scanner("System.in"); Passes a string literal instead of the actual stream object. Scanner reads from the string, not the keyboard.
Scanner keyboard = Scanner.create(System.in); No static factory method create() exists in the Scanner class.

Each of these traps targets a specific gap in understanding — forgetting new, confusing case sensitivity, or mixing up input and output streams. Studying these alternatives carefully ensures you can recognize the correct answer even when the options are designed to mislead.

Understanding System.in

System.in is a static field of the java.lang.System class. It is an instance of InputStream, Java's abstract class for reading bytes. It is automatically connected to the standard input of the process — which, in a typical console application, is the keyboard.

what would be printed out as a result of the following code?
what would be printed out as a result of the following code?

What Is an InputStream?

An InputStream is a sequence of bytes. When you type on a keyboard, each keystroke generates a byte (or sequence of bytes for non-ASCII characters). System.in collects these bytes and makes them available to your program. On its own, InputStream only provides a read() method that returns one byte at a time — extremely tedious for reading strings or numbers.

This is precisely why wrapping System.in in a Scanner is so useful. The Scanner buffers the byte stream and provides high-level methods to extract structured data. It is the same principle behind wrapping a FileInputStream in a BufferedReader for file I/O — abstraction layers that make the developer's life easier.

Buffered vs. Unbuffered Input

When you type into a console application in Java, input is typically line-buffered by the operating system. This means your keystrokes are not sent to the program until you press Enter. The Scanner reads from this buffered line and tokenizes it based on delimiters. Understanding this distinction is important when debugging input-related bugs — particularly the well-known newline in buffer problem that arises when mixing nextInt() with nextLine().

If you are curious about scanning in a different context — for example, understanding how network tools read port states — our article on which states can be returned by a port scanner provides a useful parallel to how scanners categorize and report what they find.

Scanner Methods for Reading Keyboard Input

Once you have correctly created your Scanner object with new Scanner(System.in), you have access to a rich set of reading methods. Knowing which method to use for which data type is just as important as knowing the correct instantiation syntax.

nextLine() vs. next()

These two methods are the source of considerable confusion:

  • nextLine() — reads the entire line up to (but not including) the newline character. Advances past the newline.
  • next() — reads a single token delimited by whitespace. Does not consume the newline.

The practical consequence: if you call nextInt() followed immediately by nextLine(), the nextLine() will appear to return an empty string. This is because nextInt() consumed the number but left the newline in the buffer, and nextLine() consumed that leftover newline. The fix is to add an extra nextLine() call after nextInt() to flush the buffer before reading a string.

Reading Integers and Doubles

The Scanner class provides dedicated methods for reading numeric data:

  • nextInt() — reads the next token as an int
  • nextDouble() — reads the next token as a double
  • nextLong() — reads the next token as a long
  • nextFloat() — reads the next token as a float
  • nextBoolean() — reads true or false

Each of these will throw an InputMismatchException if the input does not match the expected type. For robust programs, wrap your Scanner reads in a try-catch block or use hasNextInt() before calling nextInt().

Best Practices When Using Scanner

Knowing the correct statement to create a scanner object for keyboard input is only the beginning. Writing production-quality code also means following established best practices around resource management, error handling, and code clarity.

Always Close Your Scanner

A Scanner wrapping System.in holds a reference to the underlying input stream. While Java's garbage collector will eventually clean this up, it is good practice to close your Scanner explicitly when you are done with it:

keyboard.close();

However, be aware that closing a Scanner wrapping System.in also closes System.in itself. If you try to create another Scanner on System.in later in the same program, it will fail. For this reason, in programs that read from the keyboard in multiple places, it is common to create a single Scanner instance and pass it as a parameter rather than creating and closing multiple instances.

Failure to close scanners is a common issue flagged by static analysis tools. Learn more about avoiding this pitfall in our dedicated article on resource leak: Scanner is never closed.

Using Try-With-Resources

Java's try-with-resources statement, introduced in Java 7, is the cleanest way to ensure your Scanner is always closed, even if an exception is thrown:

try (Scanner keyboard = new Scanner(System.in)) {
    System.out.print("Enter your name: ");
    String name = keyboard.nextLine();
    System.out.println("Hello, " + name + "!");
}

The Scanner is automatically closed when the try block exits, whether normally or via exception. This pattern eliminates the risk of resource leaks and is considered best practice in modern Java development. Note, however, the same caveat applies: this will also close System.in, so use it in contexts where you do not need to read from standard input again afterward.

Scanner vs. BufferedReader: A Comparison

Developers sometimes debate whether to use Scanner or BufferedReader for keyboard input. Both are valid approaches, but they have different trade-offs worth understanding.

Feature Scanner BufferedReader
Package java.util java.io
Instantiation for keyboard new Scanner(System.in) new BufferedReader(new InputStreamReader(System.in))
Parsing numbers Built-in (nextInt(), etc.) Manual (Integer.parseInt(br.readLine()))
Performance Slightly slower (tokenizing overhead) Faster for large volumes of input
Exception handling Unchecked exceptions Throws checked IOException
Newline handling Complex (mixed token/line reads) Simpler (always reads full line)
Best use case Beginner programs, exam questions High-performance competitive programming

For the vast majority of coursework and everyday applications, Scanner is the right choice. It requires fewer lines of code, handles type parsing automatically, and is what most Java textbooks teach. BufferedReader shines in competitive programming contexts where input volume is high and speed is critical.

If you are working with documents and need to understand how scanning works in the physical hardware world, our guide to scanner devices covers the full landscape of document and image scanners available today. The conceptual parallel — a device that reads raw input and converts it into structured, usable data — is more apt than it might first appear.

At its core, the question of which statement correctly creates a scanner object for keyboard input tests your understanding of object instantiation, the Java type system, and the relationship between high-level abstractions and low-level streams. Mastering these fundamentals pays dividends far beyond a single exam question. Every Java application that reads user input relies on the same principle: wrap a source in a Scanner, call the right methods, and always manage your resources responsibly.

Frequently Asked Questions

Which statement correctly creates a Scanner object for keyboard input in Java?

The correct statement is Scanner keyboard = new Scanner(System.in);. This creates a new Scanner instance by passing System.in — Java's standard input stream connected to the keyboard — as the constructor argument. You must also import java.util.Scanner at the top of your file for this to compile.

Why must you pass System.in to the Scanner constructor for keyboard input?

System.in is the standard input stream of the Java process, which by default is connected to the keyboard. Passing it to the Scanner constructor tells the Scanner to read bytes from that stream. Without it — or if you pass a different argument like a file or string — the Scanner reads from a different source and does not respond to keyboard input.

What happens if you forget to import java.util.Scanner?

The compiler will throw a "cannot find symbol" error because it does not recognize the Scanner identifier. Java does not automatically import classes outside of java.lang, so any class from other packages, including java.util.Scanner, must be explicitly imported with an import statement before it can be used.

What is the difference between Scanner's next() and nextLine() methods?

next() reads a single whitespace-delimited token and does not consume the newline character at the end of the line. nextLine() reads everything up to and including the newline, consuming the entire line. Mixing nextInt() or next() with a subsequent nextLine() call is a common source of bugs because the leftover newline gets consumed by nextLine(), making it appear as if no input was entered.

Do you need to close a Scanner that wraps System.in?

It is good practice to close any resource you open, and Scanner is no exception. However, closing a Scanner that wraps System.in also closes System.in itself, which cannot be reopened. If your program reads from the keyboard in multiple places, create a single Scanner instance and share it rather than opening and closing multiple instances. Use try-with-resources for automatic cleanup in scoped contexts.

Can Scanner read input from sources other than the keyboard?

Yes. The Scanner class is flexible and can read from any InputStream, Readable, file, or string. Common alternatives to System.in include new File("data.txt") for file input and a String literal for parsing in-memory text. The methods you use — nextLine(), nextInt(), etc. — remain the same regardless of the input source, making Scanner a versatile tool for many input scenarios.

Rachel Chen

About Rachel Chen

Rachel Chen writes about scanners, laminators, and home office productivity gear. She started her career as an office manager at a midsize law firm, where she was responsible for purchasing and maintaining all of the document handling equipment for a 60-person staff. That experience sparked a deep interest in archival workflows, paperless office setups, and document preservation. Rachel later earned a bachelor degree in information science from Rutgers University and now writes full time. She is a strong advocate for ADF reliability over raw resolution numbers and has tested every major flatbed and document scanner sold in the United States since 2018.

Check the FREE Gifts here. Or latest free books from our latest works.

Remove Ad block to reveal all the secrets. Once done, hit a button below