Abstract
In any interactive application or program, 'User Input' is indispensable. User Input
refers to the data that a user provides to a program for it to function appropriately.
Specifically in Java, understanding how to take input in Java is a crucial skill for
any developer.
If you're wondering how to take input in java from user, three classes designed for
this: BufferedReader, Scanner, and Console.
Among these, when you're figuring out how to take input in Java, Scanner class
often comes up as it is straightforward to use.
Introduction to using input in Java
An integral part of any program is to take inputs from its user. Oracle
Corporation claims that Java is used on 3 billion devices all around the globe, and
hence to fulfill all the user’s demands, it provides all the necessary means required
to take input of any form.
In Computer Science, input refers to any data that is provided to the computer by
any means. There are mainly three types of user inputs:
Keyboard Interactions: User can provide various types of inputs to a
program through the keyboard, which can be interpreted as letters, numbers,
etc.
Command Line Arguments: In order to run our program, we need to
provide the instructions through the command line. These commands allow
the JVM (Java Virtual Machine) to recognize the program, which it needs to
compile into a byte file and later run for execution.
Files: For systemized storage of all interrelated data, we all choose file
storage. A File can be provided as user input to a program by specifying its
location in the program or as user input, as shown below in the code snippet:
import [Link]; // Import the File class
File myObj = new File("[Link]"); // Specify the filename
Our major focus in this article will be to dwell upon the inputs we can take from
the keyboard/console. This mostly covers the primitive data types such
as int, double, long, byte, etc.
See Also: Complete Java Tutorial
3 Ways to read input in Java with examples
We can take user input in java using the following three classes:
Buffered Reader
Scanner
Console
Using Buffered Reader Class
This is the most primitive method (introduced in JDK 1.0) offered by Java for
taking user inputs. The name tells about its main function, which is to provide a
buffer for data. This buffer stores the input given by the user, which is transferred
through the input stream.
It wraps the [Link] in InputStreamReader, which is later wrapped
under BufferedReader.
It can also read input from users through the command line.
Syntax
BufferedReader reader = new BufferedReader(
new InputStreamReader([Link]));
Example
import [Link];
import [Link];
import [Link];
public class BufferedReaderExample {
public static void main(String[] args) throws IOException {
InputStreamReader input = new
InputStreamReader([Link]);
BufferedReader reader = new BufferedReader(input);
[Link]("Please enter the input: ");
String name = [Link](); // input string
[Link]("You entered: ");
[Link](name);
// Closing to avoid memory leak.
[Link]();
}
}
Output
Please enter the input: Hello World
You entered: Hello World
Advantages
1. It is the most efficient method for reading input.
2. It works better when we read files because of its large buffer size.
3. We can use it while working on multiple threads.
4. There is no ambiguity related to taking multiple inputs through
the readLine() method.
Disadvantages
1. We may need to specify the buffer size (in bytes) even though the default
size is itself very large. We can specify the buffer size in
the BufferedReader constructor as follows:
InputStreamReader input = new InputStreamReader([Link]);
// Creating a buffer of size 16 KB
BufferedReader reader = new BufferedReader(input, 16384);
2. It can only take string inputs. For other data types, we need to convert the
String input to that data type using the corresponding parse function such
as [Link](), [Link](), etc.
3. We need to import multiple libraries into our program to take input through
the BufferedReader class.
Using Scanner Class
This is the most widely used method for taking inputs in a java program. It uses
the Scanner class, which provides us with specific methods to parse the input given
to the program using specific methods listed below. We can also read user input in
the command line using the Scanner class.
Syntax
Scanner scannerVariable = new Scanner([Link]);
Example
import [Link];
class ScannerClassExample {
public static void main(String args[])
{
// Using Scanner for Getting Input from User
Scanner input = new Scanner([Link]);
String name = [Link](); // string input
[Link]("You entered string: " + name);
int age = [Link](); // integer input
[Link]("You entered integer: " + age);
float percentage = [Link](); // float input
[Link]("You entered float: " +
percentage);
// Closing to avoid memory leak.
[Link]();
}
}
Output
Hello
You entered string: Hello
12
You entered integer: 12
92.6
You entered float: 92.6
Advantages
1. Easy to implement and hence widely used.
2. Better compatibility with smaller data types, and it is generally the best
option for Competitive Coding.
3. Provides convenient methods for parsing the primitive data types, which are
easy to memorize (ex. nextInt(), nextFloat(), …) from the tokenized input.
4. Regular expressions can be used to find tokens. Reading methods are not
synchronized.
5. Offers a much easier approach to reading records from a data file.
Disadvantages
1. It is slower as compared to the BufferedReader class.
2. It fails to perform efficiently for larger inputs as its buffer size is - 1KB char
buffer, which is very small when compared to that of BufferedReader (8KB
byte buffer).
3. It is not synchronous, and it does not deliver appropriate performance when
we work with multiple threads.
Using Console Class
This method is usually used for inputting passwords. In addition, it can be used for
reading password-like input without echoing the characters entered by the user.
The format of the input string syntax can also be used (like [Link]()).
The console class has no buffer when reading from the system console, but it has a
buffered output stream to write to the system console.
We need to add the [Link] library to implement
the [Link]() function.
Syntax
Console c = [Link]();
Example
import [Link];
public class ConsoleClassExample {
public static void main(String[] args) {
Console c = [Link]();
[Link]("Enter your name: ");
String n = [Link](); // string input
[Link]("Welcome " + n);
}
}
Output
Enter your name: Home
Welcome Home
Advantages
1. It allows us to enter passwords into our system with security as it does not
make the password visible while typing it.
2. We can use the format of strings to specify the input strings format.
3. The methods used by this class are synchronized.
Disadvantages
1. This method fails to work in interactive environments like IDEs where all
the input is not given at once.
2. The method does not allow us to utilize shortcuts offered by popular
compilers like Visual Studio Code and IntelliJ.
Example: Using Java Command-Line Arguments of the
main() method
We can provide inputs to our program through the Command Prompt just the
moment after we begin to execute our program.
Java programs are compiled and run by
Compile > javac [Link]
Run > java filename
These inputs are to be added just after the filename in the run command. These
inputs are dealt with by JVM (Java Virtual Machine). They are taken as strings
and passed to the main function as its parameters.
public class CommandLineArguments {
public static void main(String[] args) {
[Link]("Number of arguments: " +
[Link]);
for (String arg : args) {
[Link]("Argument: " + arg);
}
}
}
Output:
javac [Link]
java CommandLineArguments Hello Java
Number of arguments: 2
Argument: Hello
Argument: Java
Explanation:
The program demonstrates how to access and display command-line arguments
passed to the Java program. The args parameter in the main() method holds the
command-line arguments as an array of strings. The program prints the total
number of arguments and displays each argument using a for-each loop.
Example 2: Get Integer Input From the User
import [Link];
public class IntegerInput {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter an integer: ");
int number = [Link]();
[Link]("You entered: " + number);
[Link]();
}
}
Output:
Enter an integer: 12
You entered: 12
Explanation:
The program prompts the user to enter an integer, reads the input using
the Scanner class, and stores it in the number variable. Finally, it displays the
entered integer.
Example 3: Get float, double and String Input
import [Link];
public class InputExample {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter a float: ");
float floatValue = [Link]();
[Link]("Enter a double: ");
double doubleValue = [Link]();
[Link](); // Consume newline character
[Link]("Enter a string: ");
String stringValue = [Link]();
[Link]("Float: " + floatValue);
[Link]("Double: " + doubleValue);
[Link]("String: " + stringValue);
[Link]();
}
}
Output:
Enter a float: 12.9
Enter a double: 13.1
Enter a string: Hello
Float: 12.9
Double: 13.1
String: Hello
Explanation:
The program demonstrates reading different types of input from the user. It
prompts the user to enter a float, a double, and a string. It uses
the nextFloat() and nextDouble() methods to read the floating-point values,
and nextLine() is used to consume the newline character before reading the string
input. Finally, it displays the entered values.
To prevent a memory leak, we must remember to close
the BufferedReader or Scanner instance once it has been created. With the Console
class, however, this is not the case; we are not required to shut off the system
console after use.
FAQs
Q: What are the three methods of how to take input in Java?
A: Taking input in Java can be accomplished through: * Command-Line
Arguments: Given to the program at execution via the command line. * User Input
with Scanner: Utilizes the Scanner class to receive input from the user during
runtime. * Input from Files: Obtains input from external file sources.
Q: How can user input be incorporated in Java?
A: To incorporate user input in Java, the Scanner class can be employed to read
input from the console or other sources. This is a common method of how to take
input from user in Java.
Q: Which function aids in taking input in Java?
A: The Scanner class in Java aids in taking input from the user. It offers multiple
methods like nextInt(), nextLine(), etc., facilitating different types of input.
Q: How is a name inputted in Java?
A: To input a name in Java, the Scanner class along with its nextLine() method can
be utilized. This is a practical example of how to take input in Java.
Q: Could you define user input in Java?
A: User input in Java refers to the data or values given by the user during the
execution of the program. It can be introduced via the command line, keyboard, or
other input sources. The Scanner class or command-line arguments are frequently
used to dynamically interact with the program, demonstrating how to take input
from user in Java.
Conclusion
1. Three classes in Java—BufferedReader, Scanner, and Console—are
instrumental in understanding how to take input in Java from the user.
2. Command Line Arguments to the main() method also offer an alternative
method for taking input in Java.
3. For a multi-threaded program, either BufferedReader or Console would be
preferable when considering how to take input from user in Java.
4. The BufferedReader and Console classes' read methods, and
the Console class's write methods are all synchronized, contrasting with
the Scanner class's unsynchronized methods, which is a significant point to
note when taking input in Java.
5. The buffer size in BufferedReader is 8 KB, whereas Scanner provides a 1
KB buffer size, and Console offers no buffer when reading from the system
console, all of which impact how to take input in Java.
6. Both Console and BufferedReader classes read the input stream directly.
Conversely, Scanner also provides data parsing methods, which is a
valuable consideration when learning how to take input from user in Java.
7. The read methods of the Scanner class tend to be slower compared to those
of BufferedReader, a vital detail to consider when taking input in Java.