What is a Scanner Class??

We can define a Scanner Class as Java user Input. So basically it means when we need to get input or you can say data from an user we use scanner class. The data can be any of the primitive types like int, double, strings etc.

This is a class which is found in a package named as java.util package.
So to use this package we simply import it like import java.util.Scanner;

To create an object of the scanner class, we need to pass a predefined object as parameter which is System.in. So let’s see the code first of creating an object of Scanner class-

Scanner sc = new Scanner(System.in);

Here System.in represents the standard input stream.

Predefined Methods in Scanner Class

There are predefined Input Types or methods available in the scanner class, Let’s see what are those types or methods-

next()It reads the user value as a String
nextByte()It reads the user value as a byte.
nextShort()It reads the user value as a short value.
nextInt()It reads the user value as an int value.
nextLong()It reads the user value as a long value.
nextFloat()It reads the user value as a float value.
nextDouble()It reads the user value as a double value.

Example Program for the Scanner Class

import java.util.Scanner;

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

System.out.println("Enter your Roll Number"); 
int rollno = sc.nextInt();

System.out.println("Enter your Name");
String name = sc.next();

System.out.println("Enter your Fee");
double fee = sc.nextDouble();

System.out.println("Roll Number:"+rollno+ '\n' + "Name:"+name+  '\n' + "Fee:"+fee);