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 optimized for basic learning, practice and more. Examples are well checked and working examples available on this website but we can't give assurity for 100% correctness of all the content. This site under copyright content belongs to Onlinetpoint. You agree to have read and accepted our terms of use, cookie and privacy policy.