Getting Input From User in Java

Introduction

 
In Java, we have many ways to get input from a user. One of the ways 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
  1. package demo;  
  2. import java.util.*;  
  3. public class Demo {  
  4.  public static void main(String args[]) {  
  5.   Scanner input = new Scanner(System.in);  
  6.   String Dept;  
  7.   System.out.print("Plz tell me your dept---");  
  8.   Dept = input.next();  
  9.   String Designation;  
  10.   System.out.print("Plz tell me your designation---");  
  11.   Designation = input.next();  
  12.   String Introduction;  
  13.   Introduction = "OK you are in " + Dept + " as a " + Designation;  
  14.   System.out.println(Introduction);  
  15.  }  
  16. }  
  • 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 by 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.