JAVA • INPUT AND OUTPUT

Scanner for Console Input — Read console input using Scanner (intro)

Learn how to make your Java programs interactive by reading user input from the keyboard.

Historical Context & Motivation

Early computer programs ran in a purely batch processing style: a programmer prepared all instructions and data in advance, submitted them, and waited for results. There was no way to pause a program and ask the user a question mid-run. As computers became more accessible in schools and offices, developers needed a simple way to create interactive programs — programs that respond to what a user types while the program is running.

Java's original release in 1995 included low-level tools for reading input, but they were clunky and error-prone. The language designers eventually introduced the Scanner class in Java 5 (2004) specifically to make reading input from the console — and other sources — much easier. Today, Scanner is one of the first tools every Java student learns.

1995
Java 1.0 Released
Java launches with System.in and BufferedReader for input, but they require lots of boilerplate code and exception handling.
2004
Java 5 — Scanner Arrives
The java.util.Scanner class is introduced, offering simple methods like nextInt() and nextLine() for reading keyboard input.
2010s
Scanner Becomes the Standard Intro Tool
AP Computer Science A and most introductory Java courses adopt Scanner as the default way to teach console input, replacing older approaches.
2020s
Still Going Strong
Although newer alternatives exist for advanced use, Scanner remains the go-to choice for interactive console programs in education and quick prototyping.

The central question Scanner answers is straightforward: How can a Java program pause, wait for the user to type something, and then store that input in a variable? Understanding this opens the door to building programs that feel alive — from simple calculators to text-based games.

Core Principles & Definitions

Before writing any code, you need to understand a few foundational ideas about how Java handles input. The console (also called the terminal or command line) is the text-based window where your program prints output and where users type input. Java represents the keyboard input stream as System.in, and the Scanner class acts as a translator between that raw stream of bytes and the data types your program needs — like int, double, or String.

1

Import the Class

Scanner lives in the java.util package. You must add import java.util.Scanner; at the top of your file before you can use it.
2

Create a Scanner Object

Declare a Scanner variable and connect it to System.in using: Scanner sc = new Scanner(System.in);. This creates the bridge between keyboard and code.
3

Call a "next" Method

Use methods like nextLine(), nextInt(), or nextDouble() to read the type of data you need. The program pauses until the user presses Enter.
4

Store the Result

Assign the value returned by the Scanner method to a variable. For example: int age = sc.nextInt(); stores the integer the user types into the variable age.
5

Close When Done

After you're finished reading input, call sc.close(); to release system resources. In short programs this is optional, but it's a good habit to develop.
✦ KEY TAKEAWAY
Think of System.in as a raw water pipe connected to the keyboard — it delivers data in a messy stream of bytes. The Scanner is like a water filter with different spouts: one spout gives you integers, another gives you text, and another gives you decimals. You just turn the right spout (call the right method), and clean, usable data flows into your variable.

Visual Explanation — The Scanner Pipeline

The diagram shows the complete data journey: the user types at the keyboard, raw bytes flow through System.in, the Scanner converts them to the right data type, and the clean value lands in your variable.

Notice how the Scanner sits between the raw input stream and your program's variables. Without it, you'd have to manually convert bytes into characters and then parse those characters into numbers — a tedious and error-prone process. The Scanner handles all of that work behind the scenes, so you only need to call one method to get exactly the data type you want.

How Scanner Works — Method by Method

Scanner provides a family of methods, each designed to read a specific data type. When you call one of these methods, the program blocks — it freezes and waits — until the user types something and presses Enter. The Scanner then attempts to interpret (or parse) the input as the requested type. If the user types text when your code expects an integer, an InputMismatchException is thrown — but for now, we'll focus on the happy path where the user types correctly.

Key Scanner Methods

Common Scanner methods for reading different data types
MethodReturnsWhat It ReadsExample Input → Result
nextInt()intNext whole number (stops at whitespace)User types 25 → variable holds 25
nextDouble()doubleNext decimal number (stops at whitespace)User types 3.14 → variable holds 3.14
next()StringNext single word (stops at space)User types hello world → variable holds "hello"
nextLine()StringEntire line up to Enter keyUser types hello world → variable holds "hello world"
nextBoolean()booleanNext true or false valueUser types true → variable holds true
⚠️ Watch Out: nextLine() After nextInt()
A common beginner trap occurs when you call nextInt() followed by nextLine(). The nextInt() method reads the number but leaves the Enter key (newline character) in the input buffer. The following nextLine() then reads that leftover newline and returns an empty string. The fix: add an extra sc.nextLine(); call right after nextInt() to consume the stray newline before reading the real line of text.

The key pattern to remember is: prompt, read, use. First, print a message telling the user what to type (using System.out.print()). Then, call the appropriate Scanner method to read their response. Finally, use the stored value in your program's logic.

Detailed Breakdown — Reading Different Data Types

Choosing the right Scanner method depends entirely on the type of data you expect the user to enter. Imagine you're building a simple student registration form: you need a name (text), an age (whole number), and a GPA (decimal number). Each of these requires a different method call, and the variable you store the result in must match the return type.

The top row shows five common Scanner methods, each color-coded by the data type they return. The bottom section demonstrates the prompt-read-use pattern with a student registration example.

One of the most important distinctions to understand is the difference between next() and nextLine(). The next() method reads only until it hits a space, making it perfect for single-word inputs like a first name. The nextLine() method reads everything the user types until they press Enter, making it the right choice when you need a full sentence or a name with spaces (like "Maria Garcia"). When in doubt about reading text, nextLine() is usually the safer choice.

Worked Example — Building a Temperature Converter

Let's build a complete program that asks the user for a temperature in Fahrenheit and converts it to Celsius. This example uses the full Scanner workflow from import to output.

Fahrenheit to Celsius Converter
1
Step 1 — Import ScannerAt the very top of your file, before the class declaration, write the import statement. This tells Java where to find the Scanner class.
import java.util.Scanner;
2
Step 2 — Create the Scanner ObjectInside your main method, create a Scanner variable connected to System.in. We'll name it sc for brevity, but you can use any valid variable name like input or keyboard.
Scanner sc = new Scanner(System.in);
3
Step 3 — Prompt the UserPrint a clear message so the user knows what to type. Use System.out.print() (not println) so the cursor stays on the same line as the prompt — this looks cleaner.
System.out.print("Enter temperature in °F: ");
4
Step 4 — Read the InputSince temperature can have decimals (like 98.6), use nextDouble() and store the result in a double variable.
double fahrenheit = sc.nextDouble();
5
Step 5 — Convert and DisplayApply the conversion formula: Celsius = (Fahrenheit − 32) × 5 ÷ 9. Store the result and print it.
double celsius = (fahrenheit - 32) * 5.0 / 9.0; System.out.println(fahrenheit + "°F = " + celsius + "°C");
6
Step 6 — Close the ScannerRelease the Scanner resource. This is good practice, especially in larger programs.
sc.close();
▶ Sample Run
Console output: Enter temperature in °F: (user types 212 and presses Enter) 212.0°F = 100.0°C

Strengths, Limitations & Common Pitfalls

Scanner is a powerful beginner tool, but like any tool, it has strengths and weaknesses. Understanding both will save you hours of debugging. Here's a clear comparison to keep in mind as you write interactive programs.

Scanner strengths vs. limitations for console input
Strengths ✅Limitations ⚠️
Easy to learn — just import, create, and call one methodThe newline-after-nextInt bug trips up nearly every beginner
Built-in type parsing — no manual conversion neededNo built-in way to validate input (user types letters when you expect a number)
Works with files, strings, and console (versatile)Slower than BufferedReader for reading large amounts of data
No external libraries needed — part of standard JavaNot thread-safe — cannot be safely shared between parallel tasks
Can read multiple data types from a single input lineMixing next(), nextInt(), and nextLine() requires careful buffer management
✦ KEY TAKEAWAY
Scanner is like a Swiss Army knife for a beginning hiker — it handles the most common tasks really well, and you can carry it everywhere without extra gear. As you gain experience and need to handle bigger jobs (reading huge files, building GUIs), you'll graduate to more specialized tools like BufferedReader or GUI text fields. But for console programs, Scanner is the right tool for the job.

Connection to Advanced Input Techniques

As your programs grow more complex, you'll encounter situations where Scanner isn't the best fit. It's helpful to know what lies ahead so you can see where Scanner fits in the bigger picture of Java I/O (input/output). The table below compares Scanner with two other common approaches you may encounter in more advanced courses or projects.

Comparing Java input approaches
FeatureScannerBufferedReaderJOptionPane (GUI)
Importjava.util.Scannerjava.io.BufferedReaderjavax.swing.JOptionPane
Input SourceConsole, file, or stringConsole or filePopup dialog box
Type ParsingBuilt-in (nextInt, nextDouble)Manual — must use Integer.parseInt()Manual — returns String only
SpeedGood for small inputsFaster for large inputsN/A (user-paced)
Best ForLearning & small programsPerformance-critical file readingSimple GUI prompts

Don't worry about memorizing BufferedReader or JOptionPane right now. The important thing is knowing that Scanner is your foundation. The concepts you're learning — prompting the user, reading input, storing it in the right variable type — transfer directly to every other input method. Once you master the Scanner workflow, upgrading to more advanced techniques later will feel natural.

Practice Problems

PROBLEM 1 — CONCEPTUAL
Explain in your own words why you need to write import java.util.Scanner; at the top of your file. What would happen if you left it out?
PROBLEM 2 — BASIC CALCULATION
Write a complete Java program that asks the user for their name and their favorite number, then prints: "Hi [name], your number doubled is [number × 2]!" Use nextLine() for the name and nextInt() for the number.
PROBLEM 3 — INTERMEDIATE
A program needs to read an integer (a student's ID) followed by a full-name string (e.g., "Jane Smith") on two separate input lines. A beginner writes: int id = sc.nextInt(); String name = sc.nextLine(); When the user types 1234 and presses Enter, name ends up as an empty string and the program never waits for the user to type a name. Explain why this happens and write the corrected code.
PROBLEM 4 — APPLIED
Write a complete program that acts as a simple tip calculator. It should ask the user for the bill total (a double) and the desired tip percentage as a whole number (an int, e.g., 18 for 18%). The program should calculate and print the tip amount and the grand total. For example, if the bill is $50.00 and the tip is 20%, output: "Tip: $10.00 Total: $60.00".
PROBLEM 5 — CRITICAL THINKING
Consider a program that needs to read three values on a single line separated by spaces: a first name (String), an age (int), and a GPA (double). For example, the user types: Alice 16 3.85 and presses Enter once. Which Scanner methods would you call, and in what order? Would nextLine() work for the name here? Explain your reasoning.

Lesson Summary

The Scanner class from java.util is the standard beginner-friendly way to read console input in Java. You create a Scanner object connected to System.in and then call type-specific methods: nextInt() for integers, nextDouble() for decimals, nextLine() for full lines of text, and next() for single words. The fundamental pattern is prompt → read → use.

The most common pitfall is the newline-after-nextInt bug — always add an extra sc.nextLine() call after nextInt() or nextDouble() if a nextLine() follows. As you advance, you'll encounter alternatives like BufferedReader for performance and GUI dialogs for graphical applications, but the core skill of reading and processing user input remains the same across all approaches.

Varsity Tutors • Java • Scanner for Console Input — Read console input using Scanner (intro)