Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
1. Java Scanner Class
2.1.
Java Scanner Class Methods
2.2.
Example of Java Scanner Class:
2.3.
Java
2.4.
Advantages of Scanner Class
2.5.
Disadvantages of Scanner Class
3.
2. Java Bufferedreader Class
3.1.
Java Buffered Reader Class Methods
3.2.
Example of Java Buffered Reader Class:
3.3.
Java
4.
Advantages of Bufferedreader Class
5.
Disadvantages of Bufferedreader Class
6.
Difference between Scanner Class vs. BufferedReader Class
7.
Which method to use in Java?
8.
Frequently Asked Questions
8.1.
What is the best way to take input in Java?
8.2.
What is the difference between next() and nextLine() in the Java Scanner Class?
8.3.
What are the three input methods in Java?
8.4.
How to take two inputs in Java?
8.5.
What is InputMisMatchException Exception in Java?
9.
Conclusion
Last Updated: Aug 7, 2024
Easy

How to Get Input from user in Java

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.

There are two ways by which we can take Java input from the user or from a file

  1. Scanner Class
  2. Buffered Class Reader


Must read-  Iteration Statements in Java, and Duck Number in Java.

1. Java Scanner Class

The Scanner class is the most widely used input method in Java. The Scanner class is used to read the input of primitive types such as int, double, long, etc., and some non-primitive types such 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.

You can also read about the topic of Java Destructor and Hashcode Method in Java.

Java Scanner Class Methods

Some of the methods available in the Java Scanner class are:

MethodDescriptionExample
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
Run Code

Output:

Input
Method
in
Java

Advantages of Scanner Class

  • 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:

MethodDescription
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
Run Code

Output:

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

 

Must Read Static Blocks In Java.

Advantages of Bufferedreader Class

  • Buffer size is larger (8KB)
  • It is faster than the Scanner class
  • No ambiguity related to nextline() method
  • Buffered Streams are synchronous

Disadvantages of Bufferedreader Class

  • 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

Package Java.utilJava.io
Inputhandles a wider range of inputshandles a wider range of inputs
Outputdoes not write anything to the output streamdoes not write anything to the output stream
Parse inputparse primitive types and strings using regular expressionsreads the input stream as it is
Data securityNo data securityNo data security
Thread synchronisationmethods not synchronisedread methods synchronized
Buffer Size1 KB8 KB by default. If needed, the buffer size can be specified in the constructor
Closingthe object needs to be close to avoid a memory leakthe object needs to be close to avoid a memory leak

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.

You can also check about Java Tokens here.

Must Read Type Conversion in Java

Frequently Asked Questions

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:

  1. Using the Scanner class for console-based input.
  2. Using the BufferedReader class for efficient buffered input.
  3. 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 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. 

Recommended Read: pwd command in linux

At the end of this blog, the characteristics of the three input methods in Java have been summarized in brief.

Also, try out some MCQs and Practice Questions on the input method in Java. 

Live masterclass