How to Take Input in Java? (With Examples)
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:
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
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 System.in in InputStreamReader, which is later wrapped under BufferedReader.
It can also read input from users through the command line.
- It is the most efficient method for reading input.
- It works better when we read files because of its large buffer size.
- We can use it while working on multiple threads.
- There is no ambiguity related to taking multiple inputs through the readLine() method.
- 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:
- 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 Integer.parseInt(), Double.parseDouble(), etc.
- 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.
- Easy to implement and hence widely used.
- Better compatibility with smaller data types, and it is generally the best option for Competitive Coding.
- Provides convenient methods for parsing the primitive data types, which are easy to memorize (ex. nextInt(), nextFloat(), …) from the tokenized input.
- Regular expressions can be used to find tokens. Reading methods are not synchronized.
- Offers a much easier approach to reading records from a data file.
- It is slower as compared to the BufferedReader class.
- 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).
- 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 System.out.printf()).
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 java.io.Console library to implement the System.console() function.
- It allows us to enter passwords into our system with security as it does not make the password visible while typing it.
- We can use the format of strings to specify the input strings format.
- The methods used by this class are synchronized.
- This method fails to work in interactive environments like IDEs where all the input is not given at once.
- 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 filename.java 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.
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
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
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.
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.
- Three classes in Java—BufferedReader, Scanner, and Console—are instrumental in understanding how to take input in Java from the user.
- Command Line Arguments to the main() method also offer an alternative method for taking input in Java.
- For a multi-threaded program, either BufferedReader or Console would be preferable when considering how to take input from user in Java.
- 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.
- 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.
- 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.
- 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.