How to get user input in Java?

Using Scanner Class

In java.util package, the Scanner class is used to get user input from the console. It is used to read the input of primitive data types like int, double, long, short, float, and byte. It is the easiest way to read user input in a Java program. The java.util package has to be imported while using the Scanner class.

The syntax of the Scanner class is given below.

Scanner sc = new Scanner(System.in);

A list of few methods used by the Scanner class to read different data types is given below:

Method

Description

int nextInt() This method reads the next token of the input as an integer.
float nextFloat() This method reads the next token of the input as a float.
double nextDouble() This method reads the next token of the input as a double.
byte nextByte() This method reads the next token of the input as a byte.
String nextLine() This method reads a string value from the user as an input.
boolean nextBoolean() This method reads the next token of the input as a boolean value.
long nextLong() This method reads the next token of the input as a long.
short nextShort() This method reads the next token of the input as a Short.

The example below illustrates how to take input from users using the Scanner class for different data types.

import java.util.Scanner;
class exp {
  public static void main(String[] args) {
    Scanner inp = new Scanner(System.in);
    System.out.println("Enter student name, age and roll no:");
    String name = inp.nextLine();
    int age = inp.nextInt();
    long roll = inp.nextLong();
    System.out.println("Name: " + name);
    System.out.println("Age: " + age);
    System.out.println("Roll no: " + roll);
  }
}

It asks for user input as below

Enter student name, age and roll no:
Koushik
21
20180022

The output is

Name: Koushik
Age: 21
Roll no: 20180022

Using BufferedReader and InputStreamReader

The BufferedReader class of Java is used to read the text from the specified source. The InputStreamReader class is used to read line-by-line data from the keyboard.

The methods read() and readLine() reads and returns the character and next line from the source.

Let us look into an example of reading user input using BufferedReader and InputStreamReader.

import java.io.*;
public class bfrdrex {
  public static void main(String args[]) throws Exception {
    InputStreamReader r = new InputStreamReader(System.in);
    BufferedReader br = new BufferedReader(r);
    System.out.println("Enter your name:");
    String name = br.readLine();
    System.out.println("Hello " + name + "\nWelcome to Java Programming");
  }
}

The user has to enter the name like below

Enter your name:
Bob

The output is

Hello Bob
Welcome to Java Programming
0 results
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions