You saw that it is easy to print output to the console window just by calling System.out.println( ). Reading from the console window isn’t quite as simple. To read console input, you first construct a Scanner that is attached to :

Scanner reads formatted input and converts it into its binary form. Scanner can be used to read input from the console, a file, a string, or any source. For example, you can use Scanner to read a number from the keyboard and assign its value to a variable. is an object of type InputStream. This stream designed to receive input data. This stream is usually connected to the keyboard at the computer where the program is run. That way, the user can type characters directly into the standard input stream.

Now you use the various methods of the Scanner class to read input. For example, the nextLine( ) reads a line of input. To read a single word, use the next( ) method. To read an integer, use the nextInt( ) method. Similarly, the nextDouble( ) method reads the next floating-point number. When you are done with a Scanner, you must close it. This is done by calling the close( ) method.

In the following program illustrate the use of the Scanner class. Note the line import java.util.Scanner; at the beginning of the program. The Scanner class is defined in the java.util package, you need to use an import directive. The program asks for the user’s name and age and then prints a name and age.


Program Source

import java.util.Scanner;

public class Javaapp {
    public static void main(String[] args) {
        Scanner input = new Scanner(;
        String name ;
        int age ;
        System.out.print("Enter your name : ");
        name =;
        System.out.print("Enter your age  : ");
        age = input.nextInt();
        System.out.println("Your name : "+name);
        System.out.println("Your age  : "+age);

Leave a Comment