Java (programming language)

Java Scanner Class | Java Scanner Demo Program


  • Purpose: The Scanner class in Java streamlines the process of obtaining user input. It parses various data types from a variety of input sources, including the keyboard, files, and strings.
  • Key Features:
    • Tokenizes input using delimiters (e.g., whitespace by default).
    • Offers methods to read various data types, including int, double, String, boolean, and more.
    • Compatible with diverse input sources, enhancing flexibility.

Creating a Scanner Object

  • Import the Scanner class:


import java.util.Scanner;
  • Construct a Scanner object:


Scanner scanner = new Scanner(; // Reads from standard input (keyboard)
Scanner fileScanner = new Scanner(new File("myFile.txt")); // Reads from a file
Scanner stringScanner = new Scanner("This is a string"); // Reads from a string

Reading Different Data Types

  • Read an integer:


int age = scanner.nextInt();
  • Read a double:


double price = scanner.nextDouble();
  • Read a String:


String name = scanner.nextLine();
  • Read a boolean:


boolean isTrue = scanner.nextBoolean();
  • Read a single character:


char initial =;

Important Considerations

  • Whitespace and nextLine(): nextInt(), nextDouble(), and similar methods consume input only up to the first whitespace character. To read an entire line, including spaces, use nextLine().
  • Closing Scanners: To release resources, consider closing Scanner objects after use:



Demo Program


import java.util.Scanner;

public class ScannerDemo {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(;

        System.out.print("Enter your name: ");
        String name = scanner.nextLine();

        System.out.print("Enter your age: ");
        int age = scanner.nextInt();

        System.out.println("Hello, " + name + "! You are " + age + " years old.");


Additional Features

  • Changing the delimiter: Use useDelimiter() to set a custom delimiter.
  • Checking for the next token: Use hasNext() methods to verify the presence of the next token of a specific type (e.g., hasNextInt(), hasNextLine()).
  • Reading tokens as specific data types: Use methods like nextInt(), nextDouble(), nextBoolean(), and next() to read tokens as specific data types.


The Scanner class empowers Java developers to efficiently gather user input and parse data from various sources. Its versatility and ease of use make it an invaluable tool for interactive programs and data processing tasks.


Learn coding the easy way. Find programming guides, examples and solutions with explanations.

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button