Java - Core Java - Scanner Class

Scanner class in Java

Scanner class is available in java.util package used to take input of the primitive types like byte, short, int, long, float, double, boolean etc. It is the easiest way to read input in a java program.

To create an object of Scanner class, we usually pass the predefined object, represents the standard input stream. We may pass an object of class File if we want to read input from a file.

To read numerical values of a certain data type XYZ, the function to use is nextXYZ(). For example, to read a value of type short, we can use nextShort()

To read strings, we use nextLine().

To read a single character, we use next().charAt(0). next() function returns the next token/word in the input as a string and charAt(0) funtion returns the first character in that string.

Program to read data using Scanner class
import java.util.Scanner;
public class ScannerDemo
    public static void main(String[] args)
        Scanner sc = new Scanner(;
        // String input
        String name = sc.nextLine();
        // Character input
        char gender =;
        // Numerical data input
        int age = sc.nextInt();
        long mobileNo = sc.nextLong();
        double cgpa = sc.nextDouble();
        // Print the values
        System.out.println("Name: "+name);
        System.out.println("Gender: "+gender);
        System.out.println("Age: "+age);
        System.out.println("Mobile Number: "+mobileNo);
        System.out.println("CGPA: "+cgpa);