Java Scanner Class

In the last lesson you learned about Java output using System.out. Real programs ask the user for input. For that, Java gives you a tool called the Scanner.

🤔 Why do we need Scanner?

Code with only hard-coded values does the same thing every run. Real software reacts to what the user gives it. Take a greeting app:

  • Without input: it can only say “Hello, Alex”, because the name is fixed in the code.
  • With input: it asks “What is your name?”, waits, then greets whoever typed.

That is what the Scanner does:

  • Reads what the user types on the keyboard.
  • Hands that text to your program as a value you can store and use.
  • Slices the keyboard’s character stream into useful pieces: one word, one line, one number.

📥 Step 1: Import Scanner

Scanner is a ready-made tool, not part of the core language. It lives in a package (a folder of tools Java ships with) called java.util. You bring it in with an import line at the top of your file, above the class:

import java.util.Scanner;
  • This says “use the Scanner tool from java.util”, so Java knows where to find it.
  • Without it, Java does not know what Scanner means and refuses to compile.
  • Any tool outside the core language is imported the same way.

🔧 Step 2: Create a Scanner

Importing only makes the tool available. Now create one and connect it to the keyboard, which Java calls System.in. Write this inside your main method:

Scanner scanner = new Scanner(System.in);

Reading it piece by piece:

  • Scanner on the left is the type: the thing we make is a Scanner.
  • scanner is the variable name we chose; input or sc would work too.
  • new builds a fresh Scanner object in memory.
  • Scanner(System.in) connects that Scanner to the keyboard.

Do not worry about new yet (the objects lessons cover it). Treat this line as the standard way to set up keyboard input; you write it the same way nearly every time.

⌨️ Step 3: Read what the user types

Now you can read input. The Scanner gives a different method for each kind of value; call the one that matches the data you expect. Here are the common ones:

Method Reads Gives you
nextLine() A whole line, until Enter is pressed String
next() A single word, stops at a space String
nextInt() A whole number int
nextDouble() A decimal number double
nextBoolean() The word true or false boolean

Most names start with next because the Scanner reads in order:

  • Each call reads the next piece, then moves forward.
  • The cursor never goes back; once a piece is read, it is gone.

Here are all three steps together. This program asks for a name and prints a greeting.

import java.util.Scanner;
public class Greeting {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("What is your name? ");
String name = scanner.nextLine();
System.out.println("Hello, " + name + "!");
}
}

The flow, line by line:

  • Import Scanner, then create one connected to the keyboard.
  • System.out.print shows the prompt without a new line, so the user types right after the question.
  • scanner.nextLine() pauses the program until the user types and presses Enter; the text is stored in name.
  • Finally we greet them with that name.

Output

What is your name? Riya
Hello, Riya!

🔢 Reading numbers

Reading numbers works the same way; you just swap the method:

  • nextInt() for a whole number, nextDouble() for a decimal.
  • The Scanner turns the typed text into a real number you can do math with.
  • nextInt() gives an actual int, not text that looks like a number, ready to add, subtract, and compare.

This program reads an age and replies.

import java.util.Scanner;
public class AgeCheck {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your age: ");
int age = scanner.nextInt();
System.out.println("Next year you will be " + (age + 1));
}
}
  • scanner.nextInt() reads the input and stores it as an int in age, then we add 1.
  • The brackets around age + 1 make Java do the math first, before joining to the text.
  • Without them, Java glues the digits onto the string instead of adding; the brackets change the meaning.

Output

Enter your age: 24
Next year you will be 25

Reading a decimal is the same idea with nextDouble(). This reads a price.

import java.util.Scanner;
public class PriceReader {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the price: ");
double price = scanner.nextDouble();
System.out.println("With tax: " + (price * 1.1));
}
}
  • scanner.nextDouble() reads a number with a decimal point, like 9.99, and stores it as a double, then we multiply.
  • Whole numbers use nextInt(); anything with a decimal point uses nextDouble(). Pick the one that fits the value.

Output

Enter the price: 9.99
With tax: 10.989

print vs println for prompts

Use System.out.print (no “ln”) for a prompt, so the cursor stays on the same line and the user types right next to your question. Use System.out.println when you want to move to a new line after printing.

🆚 next() vs nextLine()

Both read text and give a String, but they stop at different points:

  • next() reads one token (a chunk with no spaces) and stops at the first space.
  • nextLine() reads the whole line, spaces and all, until you press Enter.

If the user types Riya Sharma and presses Enter:

  • next() grabs only Riya and leaves Sharma waiting.
  • nextLine() grabs the full Riya Sharma.

The rule is simple:

  • Use next() for one word.
  • Use nextLine() for answers with spaces, like a full name or sentence.
  • Picking the wrong one is a common cause of “why did half my input disappear?”.

✔️ Reading true or false

nextBoolean() reads the word true or false and gives a real boolean, handy for yes/no questions. This program asks if the user agrees.

import java.util.Scanner;
public class AgreeCheck {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Do you agree? (true/false) ");
boolean agreed = scanner.nextBoolean();
System.out.println("You answered: " + agreed);
}
}
  • scanner.nextBoolean() only accepts true or false; any case works, so TRUE is fine.
  • Anything else, like yes, causes an error, so use it only when the user will type a real boolean word.

Output

Do you agree? (true/false) true
You answered: true

🧹 Closing the Scanner

When you finish reading, close the Scanner. It holds a resource (here, the connection to the keyboard), and closing it lets Java release that cleanly. You do it with scanner.close() at the end.

Scanner scanner = new Scanner(System.in);
// ... read input here ...
scanner.close(); // ✅ release the resource when finished
  • In small practice programs, forgetting to close it does no harm; the program ends and Java cleans up.
  • In bigger programs with many resources, leaving them open can slowly cause problems, so build the habit now.
  • Once you call close(), you cannot read from that Scanner again, so close it only when you are truly finished.

⚠️ Common Mistakes

A few Scanner errors come up again and again. Name them and you can spot them fast.

  • Forgetting the import. Without the import line, Java does not know the type at all.
// ❌ no import, so Java does not recognise Scanner
Scanner scanner = new Scanner(System.in);
// ✅ add this line at the top of the file first
import java.util.Scanner;
  • Using the wrong method for the type. Calling nextInt() when the user types text causes an error called an InputMismatchException. Match the method to what you actually expect.
int age = scanner.nextInt(); // ❌ crashes if the user types "twenty"
String age = scanner.nextLine(); // ✅ reads any text safely
  • The newline trap after nextInt(). nextInt() reads the number but leaves the Enter key in the buffer, so a following nextLine() grabs that leftover Enter and returns an empty line. The full fix is in the Common Scanner Mistakes lesson.

✅ Best Practices

Build these habits now and your input handling stays clean.

  • Import Scanner first. Put import java.util.Scanner; at the top of your file, above the class.
  • Show a clear prompt. Tell the user exactly what to type before you read. Use print so they type on the same line.
System.out.println("Age:"); // ❌ vague, and cursor jumps to a new line
System.out.print("Enter your age: "); // ✅ clear, and types stay inline
  • Match the method to the data. Use nextInt() for whole numbers, nextDouble() for decimals, nextLine() for text with spaces, and next() for a single word.
  • Close the Scanner when done. Call scanner.close() at the end, after your last read.

🧩 What You’ve Learned

You can read input now. The key points:

  • ✅ The Scanner class reads what the user types on the keyboard.
  • ✅ You must import it with import java.util.Scanner; at the top of your file.
  • ✅ You create one with Scanner scanner = new Scanner(System.in);.
  • ✅ Read text with nextLine(), one word with next(), whole numbers with nextInt(), decimals with nextDouble(), and true/false with nextBoolean().
  • next() stops at a space, while nextLine() reads the whole line.
  • ✅ Show a clear prompt before reading, and close the Scanner when done.

Check Your Knowledge

Test what you learned. Pick an answer for each question, then click Check.

  1. 1

    What must you write at the top of your file to use Scanner?

    Why: Scanner lives in java.util, so you import it with import java.util.Scanner; at the top.

  2. 2

    How do you create a Scanner that reads from the keyboard?

    Why: System.in is the keyboard input, so new Scanner(System.in) connects the Scanner to it.

  3. 3

    The user types 'Riya Sharma'. What does next() return?

    Why: next() reads one token and stops at the space, so it returns only Riya. Use nextLine() to get the whole line.

  4. 4

    Why use System.out.print instead of println for a prompt?

    Why: print keeps the cursor on the same line, so the user's typing appears next to the prompt.

🚀 What’s Next?

You can read a single value now. Next, let’s practise reading several different inputs in one program and using them together, so the whole thing feels like a real interactive app.

Java Reading String Input

Share & Connect