Java Basics, Java Programming · December 2, 2026

Java for Beginners, Lesson 10: Taking Input with the Scanner Class

Java for Beginners · Module 2: Building Blocks


🎯 Why Do We Need Input?

A program that always prints the same answer is not very useful. Real programs ask the user for data: a name, a marks list, an amount. In Java, the easiest way to read keyboard input is the Scanner class.

📌 Scanner is a ready-made class in java.util that reads values from the keyboard, a file or a String. To use it you import it, create a Scanner object with System.in, and call methods like nextInt() and nextLine().

1️⃣ The Three Steps to Use Scanner

Keyboard
you type: 19 ⏎
➜
System.in
raw bytes
➜
Scanner
turns text into int, double, String
➜
Your variable
int age = 19

Figure 1: How Scanner turns keyboard input into values.

  1. Import it: import java.util.Scanner; at the top of the file.
  2. Create it: Scanner sc = new Scanner(System.in);
  3. Read with it: sc.nextInt(), sc.nextDouble(), sc.nextLine() and so on.

Here System.in means “the keyboard”. It is the input partner of System.out, which means “the screen”.

2️⃣ Scanner Methods

MethodReadsStops at
nextInt()an intwhitespace
nextLong()a longwhitespace
nextDouble()a doublewhitespace
nextBoolean()true or falsewhitespace
next()one word (String)whitespace
nextLine()the whole line (String)Enter key

Figure 2: The Scanner methods you will use most.

Program 1: Read a name, age and CGPA

import java.util.Scanner;

public class ReadBasics {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter your name: ");
        String name = sc.nextLine();
        System.out.print("Enter your age: ");
        int age = sc.nextInt();
        System.out.print("Enter your CGPA: ");
        double cgpa = sc.nextDouble();
        System.out.println("Name : " + name);
        System.out.println("Age  : " + age);
        System.out.println("CGPA : " + cgpa);
        sc.close();
    }
}
🖥️ Output (bold = what the user types):
Enter your name: Ajay Dabade
Enter your age: 19
Enter your CGPA: 8.75
Name : Ajay Dabade
Age : 19
CGPA : 8.75
  • Use print (not println) for the prompt so the cursor stays on the same line.
  • nextLine() reads the full name, including the space.
  • nextInt() and nextDouble() read the number and convert it for you. No parsing is needed.
  • sc.close() releases the keyboard when you are done.

3️⃣ Reading Several Numbers

Numbers can be typed on one line separated by spaces, or on different lines. Scanner treats spaces and Enter the same way when reading numbers.

import java.util.Scanner;

public class SumOfThree {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter three numbers: ");
        int a = sc.nextInt();
        int b = sc.nextInt();
        int c = sc.nextInt();
        int sum = a + b + c;
        double avg = sum / 3.0;
        System.out.println("Sum     = " + sum);
        System.out.printf("Average = %.2f%n", avg);
    }
}
🖥️ Output:
Enter three numbers: 10 20 30
Sum = 60
Average = 20.00
  • Each nextInt() picks the next number and skips the spaces.
  • sum / 3.0 uses a decimal divisor, so the average keeps its fraction (see Lesson 9).

4️⃣ The Newline Trap: nextInt() then nextLine()

This is the most common Scanner bug. nextInt() reads only the digits and leaves the Enter key (the newline) waiting in the buffer. A following nextLine() reads that leftover and returns an empty String.

Buffer after typing
19⏎Rahul⏎
➜
nextInt() takes 19
leaves ⏎ behind
➜
nextLine() reads up to that ⏎
gets an empty String
Fix: call an extra nextLine() after nextInt() to throw away the leftover Enter.

Figure 3: The leftover newline trap.

Program 2: The bug

import java.util.Scanner;

public class NewlineTrap {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Age: ");
        int age = sc.nextInt();
        System.out.print("Name: ");
        String name = sc.nextLine();
        System.out.println("Age = " + age + ", Name = [" + name + "]");
    }
}
🖥️ Output (the program never waits for a name):
Age: 19
Name: Age = 19, Name = []

Program 3: The fix

import java.util.Scanner;

public class NewlineFix {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Age: ");
        int age = sc.nextInt();
        sc.nextLine();                 // consume the leftover Enter
        System.out.print("Name: ");
        String name = sc.nextLine();
        System.out.println("Age = " + age + ", Name = [" + name + "]");
    }
}
🖥️ Output:
Age: 19
Name: Rahul
Age = 19, Name = [Rahul]
  • The square brackets in the output make the empty name easy to see.
  • The extra sc.nextLine(); simply throws the leftover Enter away. This is needed whenever nextLine() follows nextInt(), nextDouble() or next().

5️⃣ Checking Before You Read

If the user types letters where a number is expected, nextInt() fails. The hasNextInt() method checks first and returns true or false, without reading anything.

import java.util.Scanner;

public class ValidInput {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter your age: ");
        if (sc.hasNextInt()) {
            int age = sc.nextInt();
            System.out.println("Age accepted: " + age);
        } else {
            System.out.println("That is not a whole number: " + sc.next());
        }
    }
}
🖥️ Output (two runs):
Run 1:
Enter your age: 21
Age accepted: 21

Run 2:
Enter your age: abc
That is not a whole number: abc
  • The if statement is covered in Lesson 16. For now, read it as “if the next item is an int, read it; otherwise report the problem”.
  • The else branch uses next() to read and show the bad word.

6️⃣ Errors Beginners Meet

Forgetting the import

public class NoImport {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        System.out.println(n);
    }
}
🖥️ Compiler message:
NoImport.java:3: error: cannot find symbol
Scanner sc = new Scanner(System.in);
^
symbol: class Scanner
location: class NoImport
NoImport.java:3: error: cannot find symbol
Scanner sc = new Scanner(System.in);
^
symbol: class Scanner
location: class NoImport
2 errors
  • Java does not know where Scanner lives. Add import java.util.Scanner; at the top. The error appears twice because the name is used twice on that line.

Typing the wrong kind of value

import java.util.Scanner;

public class BadInput {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        System.out.println(n);
    }
}
🖥️ Runtime error (user types abc):
abc
Exception in thread “main” java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:947)
at java.base/java.util.Scanner.next(Scanner.java:1602)
at java.base/java.util.Scanner.nextInt(Scanner.java:2267)
at java.base/java.util.Scanner.nextInt(Scanner.java:2221)
at BadInput.main(BadInput.java:6)
  • The program compiles, but crashes when the user types letters for an int. Use hasNextInt() to check first, or handle the error with exceptions (Lesson 28).

⚠️ Common Mistakes

MistakeProblemFix
Missing import java.util.Scanner;cannot find symbolAdd the import
nextLine() right after nextInt()Reads an empty StringAdd an extra nextLine()
Using next() to read a full nameStops at the first spaceUse nextLine()
Creating a new Scanner for every readWasteful and can lose inputCreate one Scanner and reuse it
Prompt with printlnInput starts on the next lineUse print
Reading a char with nextChar()No such methodUse sc.next().charAt(0)

❓ Frequently Asked Questions

Q1. Why do we write System.in?
It tells Scanner to read from the keyboard. A file or a String could be given instead.

Q2. Do I have to call close()?
It is good practice, and it releases the resource. In small programs forgetting it does no harm, but never close a Scanner on System.in if you still need to read from the keyboard later.

Q3. How do I read a single character?
Scanner has no nextChar(). Read a word and take its first letter: char c = sc.next().charAt(0);

Q4. Is there another way to read input?
Yes, BufferedReader is faster for large inputs and is used in competitive programming. Scanner is simpler for learning.

✅ Key Takeaways

  • Import java.util.Scanner, create new Scanner(System.in), then call its methods.
  • nextInt(), nextDouble(), next() stop at whitespace. nextLine() reads the whole line.
  • After nextInt() or nextDouble(), add an extra nextLine() before reading a full line.
  • Use hasNextInt() to check input before reading it.
  • Typing the wrong kind of value causes InputMismatchException.
🎓 Practice questions: (1) Write a program that reads two numbers and prints their sum, difference and product. (2) Read a student’s name and three subject marks, then print the total and percentage. (3) Why does nextLine() return an empty String after nextInt()? (4) How would you read a single character from the keyboard? (5) Write a program that reads the radius of a circle and prints its area using Math.PI.
All 30 lessons in this series (open course page)

Module 1 · Getting Started

Module 2 · Building Blocks

Module 3 · Operators

Module 4 · Control Flow

Module 5 · Data and Methods

Module 6 · Objects and Revision