×

Different Ways to Take Input from User in Java

Any information provided to a system for use is known as user input. Any responsive software or application must include user input. In Java, there are 4 different ways to read the input from the user.

1. By using the Buffered Reader

2. By using Scanner Class

3. By Using Console Class

4. By using the Command line arguments

1. By using the Buffered Reader

This is the standard Java method for processing input, first implemented in JDK1.0. This technique allows us to read data from the command-line interface user by encasing the System. in (classic input stream) in an InputStreamReader that encases a BufferedReader.

  • For effective reading, the data is buffered.
  • It's difficult to recall the wrapper code.

Filename: Bufferreader.java

// Program for the implementation of a buffered reader for reading the input from the user
//importing required packages
import java.io.*;
import java.util.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Bufferreader {
public static void main(String[] args) throws IOException
{
// the value entered by the user using Bufferedreader
BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
// The input data is read using the readLine() method
String str = read.readLine();
// displaying the input value
System.out.println("The entered value is: "+str);
}
}

Output

Sai ram
The entered value is: Sai ram

Advantages

  • It is the approach for getting the most effective input.
  • The big buffer size makes it more effective while reading files.
  • It may be used while managing many threads.
  • The readLine() method's ability to accept multiple inputs is simple.

Disadvantages

  • Strings only be entered into it. About other data types, we must transform the input String to that type of data using the appropriate parse method, such as Double.parseDouble(), Integer.parseInt(), etc.
  • We must import many libraries to accept input using the BufferedReader class in our Program.

2. By using Scanner Class

The most recommended way to obtain input is generally by Scanner Class. Could use the Scanner class to read input from the command-line interface in addition to its primary function of parsing primitive types and texts using regular expressions.

  • There are practical ways to extract primitives from the tokenized input, such as nextInt(), nextFloat(), etc.
  • Tokens may be located using regular expressions.
  • The reading techniques need to be in synchronization.

Filename: ScannerClassEx.java

// Program for the implementation of a Scanner class for reading the input from the user
//importing required packages
import java.io.*;
import java.util.Scanner;
class ScannerClassEx{
    public static void main(String args[])
    {
        // Scanner class from util package is used to read input
        Scanner sc = new Scanner(System.in);
        String place= sc.nextLine(); // the input of string
        System.out.println("The entered string is: " + place);
        int ages = sc.nextInt(); //the integer value input
        System.out.println("The  entered integer value is: " +ages);
        float height = sc.nextFloat(); // The floating point input
        System.out.println("The float value is: " + height);
        // closing the method 
        sc.close();
    }
}

Output

Ramu
The entered string is: Ramu
13
The  entered integer value is: 13
5.6
The float value is: 5.6

Advantages

  • Easily implemented and hence popular.
  • It is often the best solution for competitive coding and has better compatible with smaller data types.
  • Supports simple ways to parse the simple-to-remember primitive data types (such nextInt(), nextFloat(), etc.) from the tokenized input.
  • To locate tokens, use regular expressions. The reading processes need to be coordinated. 
  • Provides a significantly simpler method for reading records from data.

Disadvantages

  • Compared to the BufferedReader class, it is slow.
  • Given that its buffer capacity is just 1KB for characters, which is extremely little compared to BufferedReader's, it cannot operate well for bigger inputs (8KB byte buffer).

3. By Using Console Class

It is used to read input that matches a password without repeating the user's input of the characters. Additionally, the syntax for the input string can be specified (just as System.out.printf()). The systems console is read from by the console class without a buffer, but it is written to via a buffered output stream. To perform the System. console() function, the java.io.Console module must be included.

Filename: ConsoleClassEx.java

//Program  for the implementation of a Console class for reading the input from the user
//importing required packages
import java.io.*;
import java.io.Console;
public class ConsoleClassEx {
  public static void main(String[] args) {
    Console con = System.console();
    System.out.print("Please enter your name: ");
    String name = con.readLine(); // The string input
    System.out.println("Hello, " + name);
  }
}

Output

Please enter your name: Vamshi.
Hello, Vamshi

Advantages

  • It enables us to securely input passwords into our System as it hides the password as we type it.
  • Input string formatting may be controlled using the format of strings.
  • This class implements synchronous methods.

Disadvantages

  • In interactive settings like IDEs in which not all input is provided at once, this approach does not function.
  • The approach prevents us from using the conveniences provided by well-known compilers like  Visual Studio and IntelliJ.

4. By using the Command line arguments

The majority of user input is for competitive coding. It would be best if you used cmd to launch these programs. By using the String format, the command-line parameters are saved. The string parameter is converted to an Integer via the Integer class's parseInt function. In the same way, during execution, for a float as well as others. Throughout this input form, the use of args[] becomes possible.

Example: Command.java

// Program is for the implementation of Command line arguments for reading the input from the user
//importing required packages
//Program to check for command line arguments
class Command{
public static void main(String[] args)
{
// the condition for finding the array length
if (args. length > 0) {
System. out.println("The arguments passed are:");
// the array args[] is iterated and prints elements
for (String value: args)
System.out.println(value);
}
else
System.out.println("There are no arguments found");
}
}

Command line arguments

javac Command.java
java Command This is the Program

Output

The arguments passed are:
This
is
the
Program

Related Topics

Java Short Keyword

Java supports eight different primitive datatypes. The language has predefined primitive datatypes that are given keyword names. Let's take a closer look at each of the eight primitive data types....

3 minutes read.

LCM Program in Java

LCM Program in Java The LCM program in Java outputs the LCM of the given numbers. In Arithmetic, the lowest common multiple, least common multiple or smallest common multiple of the...

6 minutes read.

Array Programs in Java

Array Programs in Java: An array is a data structure that stores similar elements in a contiguous memory location. In Java, an array is an object that stores the same...

7 minutes read.

Virtual Function in Java

In the Operated Oriented Programming language, a virtual function or virtual method is a collection of functions that overrides the functionality of a function in an inheriting class with the same...

4 minutes read.

Creating API Document Javadoc tool

The JavaDoc utility is a document generator tool written in Java that generates standard documentation in HTML format. It parses declarations and documentation in a source file collection that describes...

3 minutes read.

Java Binary Operators

In this article, we are going to discuss about the binary operators in Java and their operations. Also, an example program will be discussed along with the operations. These are...

6 minutes read.

Difference between String and Char Array in Java

We are heading to examine some significant differences between String and Character arrays. Both char arrays and String hold the series of characters and are utilised as a cluster of...

3 minutes read.

Special Operators in Java

An operator in Java is a special symbol. It is used to perform operations on two or more variables.  We all know basic operations in Java. There are 8 types...

5 minutes read.

Java Pi

What is Pi? There are many formulas in geometry that employ the Pi constant to calculate things like circumference, area, and volume. A circle's circumference divided by its diameter yields a...

3 minutes read.

Java Swing Time Picker

Prerequisites In this tutorial, we will learn the time picker in java swing. Before learn time picker, we should learn about java swing. Java Swing Introduction The Java Foundation Classes include Java Swing....

5 minutes read.

Basic Terms in Multithreading

To understand the terms of multithreading, we must have knowledge about concurrency, processes, and threads. Concurrency The concurrency stands for performing multiple tasks at the same time. In the process communication, the operating system permits the process...

8 minutes read.

Method chaining in Java

Method chaining in Java is the act of calling a series of methods one after the other. The sole distinction between it and function Object () constructor chaining is the difference...

3 minutes read.

Advantages of Generics in Java

Generic offers a variety of benefits. The programmer's life is made easier by using generic Java. In this section, we are going to discuss about Java's generic’s and its benefits. 1....

4 minutes read.

Difference between throw and throws in java

This article shows you the core difference between “throw” and “throws”keywords in Java programming language.The throw keyword tells Java you want another part of the code to deal withthe exception,...

2 minutes read.

How to Convert Integer to String in Java

How to Convert int to String in Java It is used when you want to convert an integer to String. You can convert int to String by using the following methods: Using...

3 minutes read.

Java Private keyword

A Java access modifier is a private keyword. It can be used to inner classes, methods, and variables. It is the type of access modifier that is most constrained. Privately declared...

4 minutes read.

Thread States in Java

An Item's Life Cycle (Thread States) A thread can be in any of the states mentioned above at any given time in Java. They are as follows: New Active I'm blocked or waiting Temporary...

3 minutes read.

Use Of Adapter class in Java

An adapter class in Java enables listener interfaces to be implemented by default. The Delegation Event Model is where the idea of listener interfaces first appeared. It is one of...

3 minutes read.

Java Destructors

Before knowing about Java destructors, let us know about constructors. If we understand the concept of the constructor, we can easily understand about destructor and also, we will get an...

3 minutes read.

Method and Block Synchronization in Java

The Synchronization is performed in multi-threading concept. The multi-threading is a concept of parallel running of a program for the execution. In the multi-threading concept, the threads are run by...

3 minutes read.