What is scanner in Java ?

Scanner Class in Java

Before introducing Scanner class and Buffer Class, let us first understand what the kinds of inputs are.

There are broadly two kinds of input: parameterized input and class-based input.

Suppose you’re asked to write a program in java that will add any two numbers.

In parameterized input, let us see what happens:

class Add
public static void main(int a, int b)
int c=a+b;
System.out.println("Sum of "+a+" and "+b+" is: "+c);

When this program is compiled and executed by clicking on

void main(int a, int b),

A dialog box appears:

The values of a and b are to be entered here in the white blanks, for e.g.:

These respective values are thrown back to the program and the same is implemented within the program to calculate the values in the code.

The output comes as:

This method of passing values during runtime to the program is called parameterized input. Any number of values can be taken as input using this method by just declaring the data type followed by a variable name. For e.g.:

void main(int a, char c, double d, float f, String s)

Note character values are enclosed within single quotes whereas string values are to be enclosed within double quotes.

Now let us discuss the class-based input system.

Class-based input system are part of packages that are declared and used to input values to a program using input console(keyboard) during runtime and thus offers a better user-program interface.

Scanner Class in Java:

Scanner Class is an Input/Output System in Java programming that is defined within a package named ‘java.util’. Thus to use scanner class, first, it should be imported as:

After importing Scanner class, we have to create an object so that we can avail the facilities of the class.

The syntax is:

Scanner <object name> = new Scanner(System.in);

Here the new keyword is used to create an object and the process is called dynamic allocation.

What is scanner in Java ?