Do you think IIT Guwahati certified course can help you in your career?
No
Introduction
In Java programming, obtaining input from the user is a fundamental task that forms the basis for interactive applications. Whether you’re developing a simple console-based program or a sophisticated GUI application, user input is crucial for dynamic and responsive behavior. Java provides several mechanisms to capture user input, each suited to different scenarios and requirements.
How to Get Input from user in Java?
There are two ways by which we can take Java input from the user or a file
The Scanner class is the most widely used input method in Java. The Scanner class is used to read the input ofprimitive typessuch as int, double, long, etc., and somenon-primitive typessuch as String, Boolean, etc.
The input is divided into tokens using a delimiter(which is whitespace by default) by the Scanner class. Methods like nextInt(), next(), nextLine(), nextFloat(), nextBoolean(), etc are used to scan the next token of the input.
The Java Scanner class is present in the Java.util package and has to be imported before using it. It extends the Object class and implements Iterator and Closeable interfaces.
Java Scanner Class Methods
Some of the methods available in the Java Scanner class are:
Method
Description
Example
nextInt()
Reads the next token of input as an int.
int num = scanner.nextInt();
nextLong()
Reads the next token of input as a long.
long num = scanner.nextLong();
nextFloat()
Reads the next token of input as a float.
float num = scanner.nextFloat();
nextDouble()
Reads the next token of input as a double.
double num = scanner.nextDouble();
nextBoolean()
Reads the next token of input as a boolean.
boolean val = scanner.nextBoolean();
nextLine()
Reads the next line of input as a String.
String line = scanner.nextLine();
next()
Reads the next complete token from the input as a String.
String word = scanner.next();
nextByte()
Reads the next token of input as a byte.
byte num = scanner.nextByte();
nextShort()
Reads the next token of input as a short.
short num = scanner.nextShort();
hasNextInt()
Checks if the next token of input can be interpreted as an int. Returns true if it can, otherwise false.
if(scanner.hasNextInt()) { ... }
hasNextLong()
Checks if the next token of input can be interpreted as a long. Returns true if it can, otherwise false.
if(scanner.hasNextLong()) { ... }
hasNextFloat()
Checks if the next token of input can be interpreted as a float. Returns true if it can, otherwise false.
if(scanner.hasNextFloat()) { ... }
hasNextDouble()
Checks if the next token of input can be interpreted as a double. Returns true if it can, otherwise false.
if(scanner.hasNextDouble()) { ... }
hasNextBoolean()
Checks if the next token of input can be interpreted as a boolean. Returns true if it can, otherwise false.
if(scanner.hasNextBoolean()) { ... }
hasNextLine()
Checks if there is another line in the input of this scanner. Returns true if another line of input exists, otherwise false.
if(scanner.hasNextLine()) { ... }
Example of Java Scanner Class:
Java
Java
// import Scanner class from java.util package import java.util.Scanner;
public class Main { public static void main(String[] args) { // create a Scanner object, sc Scanner sc = new Scanner("Input Method in Java"); // check if the scanner has token in the input while (sc.hasNext()) { // prints the token System.out.println(sc.next()); } // close the scanner sc.close(); } }
You can also try this code with Online Java Compiler
It parses the user input and reads it in the desired data type.
Each word in a string is obtained as a token and handled separately, making string manipulation easier.
Easier to read data from files.
Disadvantages of Scanner Class
Buffer size is less (1KB char buffer)
Not safe for multithreaded programs
There is ambiguity related to the nextLine() method as Scanner skips nextLine() after the use of any other next method like nextInt().
2. Java Bufferedreader Class
The Java BufferedReader class reads the stream of characters from the character input stream. The BufferedReader class is present in the Java.io package and has to be imported before using it. It inherits the abstract Java Reader Class. This is probably the best input method in Java.
When the buffered character input stream is created, an internal buffer is set automatically. This buffer, by default, has a size of 8KB, which can be changed using the BufferedReader(Reader, int) constructor. While the read operation is performed in BufferedReader.
A chunk of characters is read from the disk and stored in this internal buffer. From this buffer, characters are read one-by-one. This reduces the communication to the disk and makes the BufferedReader fast and efficient.
Java Buffered Reader Class Methods
Some of the methods available in the Buffered Reader class are:
Method
Description
int read()
int read() is used to reads a single character
String readLine()
readLine() is used to reads a line of text
int read(char[] array)
(char[] array) is used to reads the characters from the reader and stores in the specified array
long skip(long n)
skip(long n) skips n characters
void close()
It closes the input stream and releases any of the system resources associated with the stream
reset()
Resets the stream to the most recent mark, allowing re-reading from that point.
ready()
Checks if the stream is ready to be read, returning true if it is.
Example of Java Buffered Reader Class:
Java
Java
// import the classes import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader;
public class Main { public static void main(String[] args) throws IOException { InputStreamReader reader = new InputStreamReader(System.in); // connect the BufferedReader stream with the InputStreamReader stream to read the line by line data BufferedReader br = new BufferedReader(reader); // initialize an empty string String str=""; // continue the loop till the user enters stop while(!str.equals("stop")){ System.out.println("Enter string: "); // input taken str = br.readLine(); System.out.println("String: "+str); } br.close(); reader.close(); } }
You can also try this code with Online Java Compiler
Enter string:
Coding
String: Coding
Enter string:
Ninjas
String: Ninjas
Enter string:
Input Method in Java
String: Input Method in Java
Enter string:
stop
String: stop
BufferReader and InputStreamReader has to be mentioned
Input passed in string format which has to be parsed into the desired data type
Difference between Scanner Class vs. BufferedReader Class
The difference between the three input methods in Java: Scanner Class, BufferedReader Class, and Console Class are:
Criteria
Scanner Class
BufferedReader Class
Console Class
Package
java.util
java.io
java.io
Input
Handles a wider range of inputs
Handles a wider range of inputs
Primarily used for reading text from the console
Output
Does not write anything to the output stream
Does not write anything to the output stream
Can write to output using System.console().writer()
Parse Input
Parses primitive types and Strings using regex
Reads the input stream as it is
Reads input as strings only using readLine() or readPassword()
Data Security
No data security
No data security
Supports secure input (e.g., password masking) via readPassword()
Thread Synchronization
Methods not synchronized
read() methods are synchronized
Thread-safe
Buffer Size
1 KB
8 KB by default (customizable via constructor)
Not applicable (managed internally)
Closing
Needs to be closed to avoid memory leaks
Needs to be closed to avoid memory leaks
No need to close explicitly (managed by JVM)
Which method to use in Java?
The input method in Java is preferred depending on the requirements of the program. Some of the situations to use a particular method are:-
The BufferedReader class is preferred to read long strings, as there is a provision to allocate extra buffer size.
The Scanner class can be used if there is a requirement to parse the input stream with a custom regular expression.
Frequently Asked Questions
What are inputs in Java?
Inputs in Java are data provided by the user during program execution, typically through the keyboard, using classes like Scanner.
What is Java input and output?
Java input and output refer to reading data (input) and displaying results (output), commonly using classes like Scanner and System.out.
How to enter input in Java?
To enter input in Java, use the Scanner class with System.in, then call methods like nextInt() or nextLine() to read data.
What is the best way to take input in Java?
The best way to take input in Java depends on the context. For console-based applications, the Scanner class is convenient. For performance-critical applications, BufferedReader is more efficient.
What is the difference between next() and nextLine() in the Java Scanner Class?
The next() method reads the input till the space character, and the nextLine() method reads the input till the line changes.
What are the three input methods in Java?
Java offers three primary input methods:
Using the Scanner class for console-based input.
Using the BufferedReader class for efficient buffered input.
Utilizing GUI components for graphical input in JavaFX or Swing applications.
How to take two inputs in Java?
To take two inputs in Java, you can use either the Scanner or BufferedReader class. For instance, with Scanner, you can sequentially call appropriate nextInt(), nextDouble(), or other methods to read two inputs. Similarly, with BufferedReader, you can read two lines or tokens as needed.
What is InputMisMatchException Exception in Java?
If the input passed does not match with the method, InputMisMatchException is thrown. For example, if a string is passed using the nextInt() method, the exception would occur.
Conclusion
In this blog, we have discussed how to get input from the user in Java. Obtaining user input in Java is a fundamental aspect of building interactive and dynamic applications. Through the exploration of various input methods like the Scanner and BufferedReader classes, as well as GUI components, we've uncovered versatile approaches to handle user interaction.