How to get the user input in Java?

You can use any of the following options based on the requirements.

Scanner class

import java.util.Scanner; 
Scanner scan = new Scanner(;
String s =;
int i = scan.nextInt();

BufferedReader and InputStreamReader classes

BufferedReader br = new BufferedReader(new InputStreamReader(;
String s = br.readLine();
int i = Integer.parseInt(s);

DataInputStream class

DataInputStream dis = new DataInputStream(;
int i = dis.readInt();

The readLine method from the DataInputStream class has been deprecated. To get String value, you should use the previous solution with BufferedReader

Console class

Console console = System.console();
String s = console.readLine();
int i = Integer.parseInt(console.readLine());

Apparently, this method does not work well in some IDEs.

Leave a Comment