Source: Introduction to Computer Science Concepts and Programming (Texas A&M University)
Tags: Java Scanner, user input Java, java.util.Scanner, nextInt, nextDouble, nextLine, System.in, keyboard input, InputMismatchException, console input Java
Difficulty: Beginner Prerequisites: Basic Java syntax, variables, data types.
The Scanner class is how your Java programs stop being one-way monologues and start having conversations with the user. Without it, your program just runs and exits. With it, you can ask the user for data at runtime and do something useful with their answers. This is foundational to every interactive Java application you will build in this course, from simple calculators to menu-driven programs. You should already be comfortable declaring variables and understand primitive data types before tackling this material.
Java's Scanner class (from the java.util package) lets you read typed input from the keyboard. You import it, create a Scanner object pointing at System.in, then call methods like nextInt() or nextLine() to grab whatever the user types. If the user types the wrong kind of data, you get an InputMismatchException.
Scanner class
A utility class in the java.util package that creates objects capable of reading user input from various sources, most commonly the keyboard (System.in).
Think of it as a translator sitting between your program and the keyboard, converting raw keystrokes into Java data types.
java.util (package)
The standard Java library package that contains the Scanner class, among many other utility classes.
In simple terms, this is the toolbox you import from when you need Scanner.
A predefined input stream in Java that represents the standard input device, which is normally the keyboard.
Think of it as the "pipe" connecting the keyboard to your program.
import statement
A line placed at the top of your Java file (before the class declaration) that tells the compiler where to find a class you want to use.
In simple terms, it is a request slip telling Java, "I need access to this class, go fetch it."
nextInt()
A Scanner method that reads the next token of input and attempts to parse it as an int.
In simple terms, it waits for the user to type a whole number and press Enter, then hands that number back to your program.
nextDouble()
A Scanner method that reads the next token and parses it as a double (decimal number).
Think of it as nextInt()'s sibling for numbers with decimal points.
next()
A Scanner method that reads the next single token (one word, delimited by whitespace).
In simple terms, it grabs one word, stopping at the first space or newline.
nextLine()
A Scanner method that reads everything from the current position to the end of the line, including spaces.
Think of it as the "give me the whole sentence" method, compared to next() which only grabs one word.
InputMismatchException
A runtime exception thrown when the Scanner receives input that does not match the expected data type (e.g., the user types letters when nextInt() is waiting for a number).
In simple terms, Java's way of saying "that is not the kind of data I asked for."
System.out.print() vs System.out.println()
print() outputs text and keeps the cursor on the same line. println() outputs text and moves the cursor to the next line.
In simple terms, use print() when you want the user to type their answer right next to the prompt. Use println() when you want a line break after the output.
The import statement must appear at the very top of your .java file, before the class declaration:
import java.util.Scanner;
Without this line, any attempt to use Scanner will cause a compilation error.
Once imported, you create a Scanner object like this:
Scanner keyboard = new Scanner(System.in);
keyboard is just a variable name you choose; it could be scanner, input, sc, or anything valid.
System.in tells Java to read from the keyboard. You could point Scanner at other sources (files, strings), but for this topic the source is always the keyboard.
You only need one Scanner object per input source. Create it once, use it throughout the program.
Each Scanner method is matched to a specific Java data type:
nextInt() for int
nextDouble() for double
nextFloat() for float
nextLong() for long
nextByte() for byte
nextShort() for short
next() for a single String token (one word)
nextLine() for a full line String (including spaces)
Typical pattern: prompt, then read.
System.out.print("Enter your age: ");
int age = keyboard.nextInt();
System.out.println("Your age is: " + age);
System.out.print() (not println) keeps the cursor on the same line so the user types right after the colon. The program blocks, waiting for the user to press Enter.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter your age: ");
int age = keyboard.nextInt();
System.out.println("Your age is: " + age);
}
}
If the user supplies the wrong data type (e.g., types "hello" when nextInt() is waiting), Java throws an InputMismatchException and the program crashes.
Best practice is to validate input before using it, or to wrap the read in a try-catch block so the program can recover gracefully rather than crashing.
Every interactive console application, from a command-line calculator to a text-based game, relies on exactly this pattern: prompt the user, read input, process, repeat. The Scanner class is also the basis for reading data from files in later chapters, because you simply swap System.in for a File object.
Students often forget the import java.util.Scanner; line and are confused by the compilation error. The error will reference Scanner as an unresolved symbol, which is Java's way of saying it has never heard of the class.
Students sometimes assume next() reads a full line. It does not. It reads only up to the first whitespace. Use nextLine() for full lines.
Students mix up System.out.print() and System.out.println() when prompting for input, then wonder why the cursor is on the next line instead of beside the prompt. Use print() for prompts.
Students forget that calling nextInt() (or nextDouble(), etc.) does not consume the trailing newline character. If you call nextLine() immediately after nextInt(), it will read that leftover newline as an empty string. The fix is to add a throwaway keyboard.nextLine() call between them.
⚠️ You will almost certainly be asked to write a short program that reads user input. Know the three-step pattern: import, create, read.
⚠️ Expect a question on what happens when the user enters the wrong data type. The answer is InputMismatchException.
⚠️ Know the difference between next() (one word) and nextLine() (full line). This is a very common exam question.
⚠️ Remember that System.out.print() keeps the cursor on the same line while System.out.println() moves it down. Exam code-tracing questions test this.
True or false: You can create a Scanner object without importing java.util.Scanner.
Fill in the blank: To read an entire line of text including spaces, use keyboard.___________().
True or false: System.out.print("Hello") moves the cursor to the next line after printing.
Fill in the blank: If the user types "cat" when the program calls keyboard.nextInt(), Java throws an ___________.
True or false: The variable name for your Scanner object must be keyboard.
Answers: 1. False. 2. nextLine. 3. False. 4. InputMismatchException. 5. False (it can be any valid identifier).
Q: Write the import statement required to use the Scanner class.
A: import java.util.Scanner;
Q: What is the purpose of System.in when creating a Scanner object?
A: System.in tells the Scanner to read input from the standard input device, which is normally the keyboard. It is the input stream source.
Q: A student writes int x = keyboard.nextDouble();. Will this compile? Why or why not?
A: No. nextDouble() returns a double, and Java will not automatically narrow a double to an int. The student needs either int x = (int) keyboard.nextDouble(); (with explicit casting) or int x = keyboard.nextInt();.
Q: Explain the difference between next() and nextLine().
A: next() reads a single token up to the first whitespace (space, tab, or newline). nextLine() reads everything from the current position to the end of the line, including spaces.
Q: What exception is thrown if the user types "abc" when the program expects an integer via nextInt()?
A: InputMismatchException.
This material connects directly to file I/O later in the course, where you swap System.in for a File object and use the same Scanner methods to read data from text files. It also ties into exception handling (try-catch), which you will learn as the standard way to deal with InputMismatchException and other runtime errors. Understanding data types here reinforces the type system concepts from earlier chapters on variables and primitive types.
Java user input, Scanner class Java, java.util.Scanner, System.in, nextInt, nextDouble, nextLine, next, keyboard input Java, InputMismatchException, console input, reading input Java, System.out.print vs println, interactive Java program, CSCE intro programming, Texas A&M CS