How to take input from user in java


In this post, we will see how to take input from user in java.

There are times when you want to take input from user and run program according to user input.

There are many ways to take input from user and some of them are:

  • Using Scanner
  • Using BufferReader

Using  Scanner class

Scanner class is a way to take input from users. Scanner class is available in java.util package so import this package when use scanner class.

Firstly we create the object of  Scanner class. When we create object of Scanner class we need to pass as a parameter which represents standard input stream and that is a predefined object. If we want to take input from a file then we have to pass object of class File.

How  to  create  object  of  scanner class :

Here  Scanner is a class, s is an object ,new is used to allocate memory and is for the standard input stream.
There are various methods available in Scanner class. Few of them are:

Method Description
nextInt() It Is used to input an integer.
nextLine() It is used input a String. It reads input including space between words.
nextFloat() It is used to input a Float.
nextByte() It is used to input a Byte.
next() It is used to input string but it read the input only till space. It can not read two words separated by space.

We can use any method according to the type of value we want to read.
Below Source code shows the use of scanner class.

When you run above program, you will get below output.

Enter Employee  name:
Enter Employee Id:
Enter Employee Salary:
Employee  details:
Employee  name is: John
Employee  id is: 101
Employee  salary is: 20000.0

Using  BufferedReader classs

By using in an InputStreamReader which is wrapped in BufferedReader, we can read input from the user in console. BufferedReader is available in package. when we take input using BufferedReader class it takes all the values as  String so, whenever any other type of values like int, float values are required. We need to parse the value which is in string form using wrapper class for ex: Integer.parseInt  for int, Float.parseFloat  for float values.


When you run above program, you will get below output.

Enter Student name:Martin
Enter Student number:
Student details:
Student name is:Martin
Student number is:101

Please note that BufferedReader class is thread safe while  Scanner class is not.

That’s about taking input from user in java.


Add Comment