Skip to main content

Java Scanner Class Example in Java

1 min read Updated May 29, 2026
Share:
On this page (8sections)

Introduction

The Scanner class in java.util is the most common way to read keyboard input in beginner Java programs. It can read integers, floating-point numbers, words and entire lines from System.in.

When to Use Scanner

Use Scanner when your program needs interactive input from the user — for example, reading a name, age or menu choice in a console application.

Example Program

import java.util.Scanner;

public class ScannerDemo {
    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 height (cm): ");
        double height = sc.nextDouble();

        System.out.println("\n--- Profile ---");
        System.out.println("Name   : " + name);
        System.out.println("Age    : " + age);
        System.out.println("Height : " + height + " cm");

        sc.close();
    }
}

Sample Output

Enter your name: Thiyagaraaj
Enter your age: 25
Enter your height (cm): 172.5

--- Profile ---
Name   : Thiyagaraaj
Age    : 25
Height : 172.5 cm

How It Works

  1. new Scanner(System.in) connects the scanner to standard input (keyboard).
  2. nextLine() reads a full line of text including spaces.
  3. nextInt() and nextDouble() parse numeric tokens from the input stream.
  4. Always call close() when finished to release the underlying stream.

Best Practices

  • Import java.util.Scanner explicitly in exam and interview programs.
  • After nextInt() or nextDouble(), consume the trailing newline with an extra nextLine() if you read text next.
  • Do not create multiple Scanner objects on System.in in the same program.

Common Mistakes

  • Mixing next() and nextLine() without understanding token boundaries.
  • Forgetting to close the scanner in long-running applications.
  • Using Scanner for file parsing when dedicated readers (BufferedReader, Files.lines) are more efficient.

Frequently Asked Questions

Why does nextInt() skip the next nextLine() call?
nextInt() reads the number but leaves the newline character in the buffer. Call nextLine() once after nextInt() to consume that leftover newline before reading a full line of text.
Should I use Scanner or BufferedReader?
Scanner is easier for mixed input types in learning programs. BufferedReader is often preferred for high-volume text I/O in production because it is faster.

Related Tutorials

Search tutorials