User Input In Java

Sometimes, we may face a situation where we need to get the input from the user in run-time. We use “Scanner” class to accept input from the user. How to take input from a user in Java is a popular interview question. We use Scanner class in Java to get input from the user. Java Scanner class comes under java.util.package. To use Scanner class, we need to import the java.util.package in our program.

Java Interview Questions

Syntax:

Sample Program:

Other ways to read input from the user in Java are as follows. In Java, there are three different ways to read input from the user.

  1. Scanner Class
  2. BufferedReader Class
  3. Console Class

We have already seen Scanner Class above. Even though Scanner Class is most preferred way to get user input in java there are other two ways to read input from the user in Java. Let’s see those now.

BufferedReader Class:

Java BufferedReader class is used to read text from input stream. It is used to buffer characters for efficient handling of characters, arrays and strings. It reads data line by line by using readLine() method. It gives fast performance.

Sample Program:

Input:

Output:

Console Class:

The Console class was introduced in Java 1.6. It is one of the preferred way by developers for reading user input from the command line. This Console class provide methods like readLine() and readPassword(). Using this readPassword method the user input will not be shown in the console. The password will be returned as an array of char.

Note: It doesn’t work on IDE’s because System.console() requires console.

You may also like:

Rajkumar SM is a founder of SoftwareTestingMaterial. He is a certified Software Test Engineer by profession and blogger & youtuber by choice. He has an extensive experience in the field of Software Testing. He writes here about Software Testing which includes both Manual and Automation Testing. He loves to be with his wife and cute little kid 'Freedom'.

2 thoughts on “User Input In Java”

Leave a Comment

Share via
Copy link
Powered by Social Snap