Methods To Take Input In Java

Methods To Take Input In Java
Methods To Take Input In Java

Introduction

In today’s world, everyone might be using Google daily to get various information. Now, what exactly is Google, and how does it work?

Google search engine is basically a software program that takes dynamic input from the user and displays the results based on the user’s need. 

Similarly, the software we use can produce the desired output only if proper input is given. This is why it is essential to learn how to take input in any program. 

Now, what are the input methods in Java?


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.

Check out the blog on the Java Scanner Class, to know more about it.

Java Scanner Class Constructors

The Scanner class has various constructors that initialize the scanner object. The various Scanner constructors are:

ConstructorsDescription
Scanner(File source)Initialises a Scanner object that produces values scanned from the file
Scanner(File source, String charsetName)Initialises a Scanner object that produces values scanned from the file using the decoding technique
Scanner(InputStream source)Initialises a Scanner object that produces values scanned from the input stream
Scanner(InputStream source, String charsetName)Initialises a Scanner object that produces values scanned from the input stream using the decoding technique
Scanner(Readable source)Initialises a Scanner object that produces values scanned from the source
Scanner(String source)Initialises a Scanner object that produces values scanned from the string
Scanner(ReadablebyteChannel source)Initialises a Scanner object that produces values scanned from the channel
Scanner(ReadablebyteChannel source, String charsetName)Initialises a Scanner object that produces values scanned from the channel using the decoding technique
Scanner(Path source)Initialises a Scanner object that produces values scanned from the specified file
Scanner(Path source, String charsetName)Initialises a Scanner object that produces values scanned from the specified file using the decoding technique

Java Scanner Class Methods

Some of the methods available in the Scanner class are:

MethodDescription
public void close()close the scanner object
public boolean hasNext()true is returned if the scanner has another token in its input 
public MatchResult match()  used to get the match result of the last scanning operation performed by the Scanner
public String next()returns the next complete token from Scanner
public boolean nextInt()  scans the next token of the input as an integer
public Scanner reset()  reset the Scanner in use
public String toString()  returns the string representation of this Scanner, which contains information that may be useful for debugging

Example:

// 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();
 }
}

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().

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 Bufferedreader Class Constructors

The various Buffered Reader constructors are:

ConstructorsDescription
BufferedReader(Reader rd)creates a buffered character input stream with a default size for the input buffer
BufferedReader(Reader rd, int size)creates a buffered character input stream with a specified size for the input buffer

Java Buffered Reader Class Methods

Some of the methods available in the Buffered Reader class are:

MethodDescription
int read()reads a single character
String readLine()reads a line of text
int read(char[] array)reads the characters from the reader and stores in the specified array
long skip(long n)skips n characters
void close()closes the input stream and releases any of the system resources associated with the stream

Example:

// 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();   
 }
}

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

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

Java Console Class

Java Console class is a built-in class used to read from and write to the console. It is attached to the system console internally. This input method in Java can be used to read passwords without displaying them on the console.

Most of the input functionalities of the Java Console class are available through System.in, and the output functionalities are available through System.out.

The Console class is present in the Java.io package. It extends the Object class and implements the Flushable interface.

Java Console Constructor

Unlike the Buffered Reader class and Scanner Class, the Java Console class does not have any constructor. Instead, the System Class provides a static method console() that returns the singleton instance of the Console class.  If a console is available, the reference to it is returned, else null is returned.

Syntax to get the instance of Console class

Console c = System.console();

Java Console Class Methods

The Java Console Class provides methods to access the character-based console device (if any) associated with the current Java Virtual Machine (JVM). Some of the methods are:

MethodDescription
Reader reader()returns the object of the Reader class related to the console
String readLine()reads a single line of text from the console
PrintWriter writer()retrieves the unique PrintWriter object associated with the console
void flush()flushes the console and forces any buffered output to be written immediately
char[] readPassword()reads password that is not displayed on the console
Console format(String fmt, Object… argsthe formatted string is displayed on the console output stream
Console printf(String format, Object… args)uses the specified format string and arguments to write a formatted string to this console’s output stream

Example:

Let’s look at a program to take a password as input using the Java Console Class and print the password as output.

// import the classes
import java.io.Console; 
 
public class Main {
 public static void main(String[] args) {
   //Obtain a reference to the console
    Console c = System.console();
    System.out.println("Enter password: ");  
   // reads password that is not displayed on the console
    char[] passwordArray = c.readPassword();
    // convert char array to string
    String password = String.valueOf(passwordArray);  
    System.out.println("Password: "+password);
 }
}

Output:

Note: Password is not displayed on the console.

Advantages of Console Class

  • Facility to protect data by not displaying the entered characters on the string
  • Read and write methods are synchronized
  • Possible to write a formatted string to the output stream 

Disadvantages of Console Class

  • It cannot work in a non-interactive environment like an IDE

Scanner Class vs. BufferedReader Class vs. Console Class

The difference between the three input methods in Java: Scanner Class, BufferedReader Class, and Console Class are:

CriteriaScanner ClassBufferedReader ClassConsole Class
Package Java.utilJava.ioJava.io
Inputhandles a wider range of inputshandles a wider range of inputsdesigned to access the character-based system console only
Outputdoes not write anything to the output streamdoes not write anything to the output streammethods available to write the prompt to the system console’s output stream
Parse inputparse primitive types and strings using regular expressionsreads the input stream as it isreads the input stream as it is
Data securityNo data securityNo data securitymethods like readPassword provide data security
Thread synchronisationmethods not synchronisedread methods synchronizedread and write methods synchronised
Buffer Size1 KB8 KB by default. If needed, the buffer size can be specified in the constructorno buffer when reading, but it has a buffered output stream while writing
Closingthe object needs to be close to avoid a memory leakthe object needs to be close to avoid a memory leakno need to close the object

Which one to use?

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 console class can be used if data security is the priority, like in programs involving passwords, pins, etc.
  • In a multi-threaded program, BufferedReader is preferred unless features specific to the Console class are required.
  • 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 is the best way to take input in Java?

The input method in Java depends on the program requirements. The majority of times, the Scanner class is used.

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 is nextLine() in the Java Scanner Class?

The nextLine() method in the Java Scanner Class returns the string from the current position to the end of the line.

What is nextInt() in the Java Scanner Class?

nextInt() scans the next token of the input as an integer while using the scanner class.

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.

Key Takeaways

That was all about the various input methods in Java. The three input methods in Java, namely the Scanner class, the BufferedReader class, and the Java Console class, are discussed in detail in this blog, along with the examples, advantages, disadvantages, etc.

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

There is one more way of passing input in Java, which is through the command-line arguments. Check out this blog to learn more about it. Also, try out some MCQs and Practice Questions on the input method in Java. 

By Hari Sapna Nair

Exit mobile version