Java Scanner Class


Java's Scanner class from the java.util package functions as a text parsing tool which can read input from multiple sources such as keyboard input (System.in), files or strings.


Syntax:

 import java.util.Scanner;

Creating a Scanner Object

Scanner scanner = new Scanner(System.in);

For reading from a file:

Scanner scanner = new Scanner(new File("input.txt"));

For reading from a string:

Scanner scanner = new Scanner("Hello World 123");;

Reading Input (From Console)

Read a Full Line

System.out.print("Enter a sentence: ");
String line = scanner.nextLine();

Read a Single Word

System.out.print("Enter a word: ");
String word = scanner.next();

Read an Integer

System.out.print("Enter an integer: ");
int number = scanner.nextInt();

Read a Double

System.out.print("Enter a decimal number: ");
double decimal = scanner.nextDouble();

Example

import java.util.Scanner;

public class ScannerExample {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

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

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

        System.out.print("Enter your height in meters: ");
        double height = scanner.nextDouble();

        System.out.println("\n--- User Details ---");
        System.out.println("Name: " + name);
        System.out.println("Age: " + age);
        System.out.println("Height: " + height + " m");

        scanner.close(); // Always close the scanner
    }
}
 

Method Description
next() Reads a single word (ends on space)
nextLine() Reads a whole line
nextInt() Reads an int
nextDouble() Reads a double
nextBoolean() Reads a boolean
hasNext() Checks if more input is available
hasNextInt() Checks if next input is an integer
close() Closes the scanner (recommended)



OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.