Getting Input From User in Java

Introduction

In Java, we have many ways to get input from a user. One of the ways to do this is the Scanner class. It is a very useful class in Java. The Scanner class takes input from the user and prints it as the output.

Scanner class

The Scanner class takes input from the user. The input is broken down into tokens by the Scanner class. White space is used as the delimiter by the Scanner class. It is the default delimiter.

Example

package demo;

import java.util.*;

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

        // Getting department input
        System.out.print("Please tell me your department: ");
        String Dept = input.next();

        // Getting designation input
        System.out.print("Please tell me your designation: ");
        String Designation = input.next();

        // Formulating the introduction
        String Introduction = "OK, you are in " + Dept + " as a " + Designation;

        // Printing the introduction
        System.out.println(Introduction);

        input.close(); // Closing the Scanner to avoid resource leak
    }
}
  • The java.util library contains the Scanner class.
  • Scanner input = new Scanner(System.in); creates the object of the Scanner class. Here new is used to create new objects of a class.
  • System.in is used to inform Java that it is the system input.
  • Here, we use the next method. The next method is used to fetch the input from the user. It will fetch the next string that is typed by the user on the keyboard.

Output

output

When we run our program, it will ask us for our first input, and when we give it then, it will give us the following output.

first input

After pressing Enter, it will again ask for the input and store the previous input into the variable Dept.

first output

When we give the second input, it will give the following output.

designation output

Now, when we press Enter again, it will show us the complete output and again store the second input into the second variable Designation.

final output

Summary

This article explains a way to get input from the user with the help of the Scanner class.


Similar Articles