Java User Input – Scanner, BufferedReader and Console

Accepting user input is a core component of creating interactive Java programs. From a console-based tool to a form-based system and even a game, knowing how to read and handle user input is very important. Java offers a number of methods – Scanner, BufferedReader, and Console – to read various kinds of input such as strings, numbers, and characters. Each input method is covered in this tutorial, along with examples, best practices, and common pitfalls for beginner and advanced programmers alike to write interactive and responsive Java programs.

Table of Contents:

Understanding User Input in Java

User input in Java is the process of getting input entered by a user when the program is running. Java offers a number of methods for reading user input, the most used being the keyboard (console input).

The input is used for creating interactive programs, such as prompting a user for their name, age, or any other information that the program will process.

Java accepts user input using three basic methods:

  • Scanner (from java.util package): Simplest and most widely used for novices.
  • BufferedReader (from java.io package): More efficient for reading large amounts of data or many lines.
  • Console (from java.io.Console): Is helpful in command-line programs but not supported in all environments (such as IDEs).

Each of these methods has different uses based on performance, simplicity and environment compatibility.

Java Training
This is comprehensive training course in Java programming language that will make you grow in your software coding career
quiz-icon

Methods for Taking User Input in Java

In Java, the user can take input using three different methods, i.e., Scanner, BufferedReader, and Console. The Scanner class is easy and reads the input from different data types such as integers, doubles, and strings. The BufferedReader class is faster and efficient for large inputs, but it requires manual conversion as throughput only comes in the form of a string. The Console class is used for secure input, such as passwords.

1. Scanner class in Java

The most common way to take the user input in Java is by using the Scanner class, which is found in the java.util package. The scanner class can read the input value from the console, files, or streams. Before Java 5, the BufferedReader class was used

This class does not require any downloads or installations. It is designed to read the primitive data types and strings by using the regular expressions. This means that it can automatically interpret the input text like integers, double values, and strings. It works in all environments, including IDEs.

To read input from the file, we can pass the object of the Scanner class in a file. The Scanner class reads an entire line and then divides it into tokens. Tokens are small elements that have some meaning to the Java compiler. 

For example, suppose there is an input string: “How are you
The scanner object will read the entire line and will divide the string into tokens, i.e., “How”, “are”, and “you”. Then the object goes to each token and reads it using the different methods.

Steps to take input from the user using the Scanner class

The following are the steps to take user input using the Scanner class:

1. Import the Scanner class using import java.util.Scanner;

import java.util.Scanner;

2. Create the Scanner object and connect Scanner with System.in by passing it as an argument, i.e.

Scanner scn = new Scanner(System.in);

3. Prompt the user for input by displaying a message.

4. Use appropriate Scanner methods to read input based on the data type required. Like nextInt(), nextLine(), next(),or nextDouble()

5. Close the Scanner to free up the resources

scn.close();

Note:  The Scanner class should be closed when it is not needed because it helps free up resources. Be careful while closing the scanner class as when it will be closed, it will also close the System.in, which can affect the other parts of the program that will read an input from the console.

Methods of the Scanner Class

The Scanner class provides various methods to read different types of input from the user:

Method Description
nextBoolean() Reads a boolean value (true or false).
nextByte() Reads a byte value.
nextDouble() Reads a double (decimal) value.
nextFloat() Reads a float (decimal) value.
nextInt() Reads an int (integer) value.
nextLine() Reads an entire line of text.
nextLong() Reads a long (large integer) value.
nextShort() Reads a short (small integer) value.
next() Reads a single word (until space).
nextBigInteger() Reads a BigInteger value.
nextBigDecimal() Reads a BigDecimal value.
hasNext() Checks if there is another token in the input.
hasNextBoolean() Checks if the next token is a boolean.
hasNextByte() Checks if the next token is a byte.
hasNextDouble() Checks if the next token is a double.
hasNextFloat() Checks if the next token is a float.
hasNextInt() Checks if the next token is an int.
hasNextLine() Checks if there is another line of input.
hasNextLong() Checks if the next token is a long.
hasNextShort() Checks if the next token is a short.

Java Scanner Delimiter 

By default, the Scanner class uses the whitespace, like spaces and the Enter key to separate the input value. However, this can be changed by using the useDelimiter() method, which allows the users to define a custom delimiter like commas, semicolons, or any other character of the users’ choice.

Example: Using a Comma as a Delimiter

Java

Output:

Java-Scanner-Delimiter

Explanation: The above code shows how to use a user-defined delimiter by using the Scanner class in Java. The useDelimiter(“,”) function is used to make the comma as the delimiter, and then the while loop reads and prints its value.  

Handling Multiple Inputs in Scanner Class

When we are taking multiple user inputs, we can add an if statement before each input, which will make the program more lengthy and complex. To reduce this, the Scanner class provides built-in exception handling.

If the input entered by the user cannot be processed correctly, the Scanner method will throw exceptions such as:

  • NoSuchElementException: It is thrown when no more input is available, but a method is called to read input.
  • InputMismatchException: It is thrown when the input does not match the expected data type e.g., entering a string when an integer is expected.

By using methods like hasNextInt(), hasNextDouble(), etc., we can check user input before reading it to avoid exceptions.

Example: Handling the Input Mismatch Exception

Java

In the above program, if the user enters an integer, no error message will be displayed, and the program will run successfully, showing the expected output.

Handling-Multiple-Inputs-in-Scanner-Class

However, if the user enters a string instead of an integer, an error message will be displayed as shown below.

Handling-Multiple-Inputs-in-Scanner-Class-1

2. BufferedReader Class in Java

The BufferedReader class in Java reads a stream of characters from a character-based input stream. It is often used with FileReader or InputStreamReader to improve performance when reading large files or streams. InputStreamReader is a function in Java that converts the input stream into a sequence of characters for BufferedReader to scan it.

The BufferedReader class uses read() and readLine() methods to read the characters from input.

Steps to take input from the user using the BufferedReader class

The following are the steps to take user input using the BufferedReader class:

1. Import the BufferedReader class using import java.io.BufferedReader;

import java.io.BufferedReader 

2. Create the BufferedReader object 

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

3. Read the Input Using readLine()

System.out.print("Enter your name: ");

String name = br.readLine();  // Reads a full line of input

4. Process the Input

System.out.println("Hello, " + name + "! You are " + age + " years old.");

5. Close the BufferedReader to free up the resources

br.close();

 Example:

Java

Output:

using-the-BufferedReader-class

Explanation: The above Java program takes user input using the BufferedReader class. Then it asks for the user’s name and reads it as a string. Further, asks for the user’s age, reads it, and converts it to an integer. Finally, it prints a greeting message and closes the BufferedReader.

Get 100% Hike!

Master Most in Demand Skills Now!

Methods of the BufferedReader Class

The following is the list of the table which shows the methods that the buffered reader uses to read the input in Java entered by the user 

Method Description
readLine() Reads a full line of text as a string.
read() Reads a single character as an integer. Returns -1 if it reaches the end of the stream.
skip(long n) Skips n characters while reading.
ready() Returns true if the stream is ready to be read, else false.
mark(int limit) Marks the current position in the stream.
reset() Resets the stream.
close() Closes the BufferedReader to free resources.

Reading Different Data Types with BufferedReader

As BufferedReader only reads strings, we need to convert input manually into the other data types.

Example: Reading an Integer

System.out.print("Enter your age: ");

int age = Integer.parseInt(br.readLine());  // Convert String to int

Example: Reading a Double

System.out.print("Enter your salary: ");

double salary = Double.parseDouble(br.readLine());  // Convert String to double

Advantages of BufferedReader 

1. Faster Input Handling: It reads the large data.

2. Efficient for Large Data: It is suitable for reading large files and processing large inputs.

3. Reads Full Lines: It can read the entire line using the readLine().

4. Less Memory Usage: It uses a buffer to store the input, which reduces the number of interactions with the input stream.

5. Supports Character Streams: It can handle the character-based input, which makes it useful for text processing.

Disadvantages of BufferedReader

1. Only Reads Strings: It only returns input in the form of strings, which requires manual conversion for numbers.

2. More Code Required: It needs an extra step to convert input data type.

3. No Built-in Input Validation: It does not check for valid input type.

4. Checked Exception Handling: It requires the handling of IOException with try-catch or the throws keyword.

3. Console Class in Java

The Console class in Java is used for reading user input from the system console command-line interface. It is part of the java.io package and is useful for interactive applications.

Advantages of console class

1. Secure Input Handling: It allows the user to securely input the password. The readPassword() method allows the users to input the passwords without displaying them on the screen, which will make it secure.

2. Ideal for Command-Line Applications: It works well in a terminal like Command Prompt, Terminal, and  PowerShell. It is good for applications where IDEs are not required, e.g., remote server applications

Disadvantages of Console Class

1. Does Not Work in IDEs: In most IDEs like Eclipse, IntelliJ, and NetBeans, System.console() returns null because IDEs do not use a system console to run the Java programs.

2. Limited Input Capabilities: It only returns the String input, i.e., you have to convert it to another data type by using Integer.parseInt(), Double.parseDouble(), etc.

Example:

Java

Output:

Disadvantages-of-Console-Class-Limited-input-capabilities

BufferedReader vs Scanner Class in Java

Let us discuss the differences between the BufferedReader class and the Scanner class in Java.

Feature BufferedReader Scanner
Speed Faster (uses buffering) Slower (token-based)
Ease of Use Requires manual conversion Easy to use
Reads Data Only strings (needs conversion) Strings, numbers, booleans
Best For Large files, performance General user input
Exception Handling Requires try-catch (IOException) Built-in exception handling
Memory Usage Low (uses buffering) Higher (parses input)
Methods readLine() nextInt(), nextLine(), nextDouble(), etc.

Let us discuss the differences between the BufferedReader class and the Scanner class in Java

Free Online Java Certification Course
This free Java course is designed for anyone interested in learning Java and pursuing a career as a Java Developer
quiz-icon

Conclusion

In Java, developers can use a Scanner, a BufferedReader, or a Console to read the user input. The Scanner is easy to use and has many data types to read an input. The BufferedReader class improves the efficiency when reading large inputs, but the data type has to be changed by the user only. The Console class handles inputs securely, such as passwords, but does not work in the IDEs. 

If you want to learn more about Java, you can refer to our Java Course.

Java User Input: Scanner, BufferedReader and Console – FAQs

Q1. How to read input from the System in Java?

For reading input, we use the Scanner tool that comes with Java

Q2. How to get input from the user in Java without using a Scanner?

Using Buffered Reader Class, it is the classical method to take input in Java.

Q3. How to call a method in Java?

To call a method in Java, you can write the method name followed by a parentheses (), and a semicolon ( ; ).

Q4. How to read a file using Java?

You can use the readLine() method from java.io.BufferedReader to read a file. This method returns null when it reaches to the end of the file

Q5. What is the difference between Scanner and BufferedReader?

In Java, BufferedReader reads text from a character input stream efficiently, while Scanner is reads input from various sources, including streams, and parse input into tokens and primitive types.

Q6. How to access a file in Java?

There are several ways to read a plain text file in Java, e.g. you can use FileReader, BufferedReader, or Scanner to read a text file. 

About the Author

Technical Research Analyst - Full Stack Development

Kislay is a Technical Research Analyst and Full Stack Developer with expertise in crafting Mobile applications from inception to deployment. Proficient in Android development, IOS development, HTML, CSS, JavaScript, React, Angular, MySQL, and MongoDB, he’s committed to enhancing user experiences through intuitive websites and advanced mobile applications.

Full Stack Developer Course Banner