×

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 Binary Tree

The non-linear data structure known as a binary tree is a type of tree, and because it stores data in a hierarchical manner, it is mostly utilised for finding and...

7 minutes read.

this keyword in Java

The 'this' keyword is an essential notion in Java. We'll go through the 'this' keyword in depth and provide some examples of how it's used in Java. In Java, the term...

5 minutes read.

Application of Array in Java

In this article we are going to acknowledge about what the array is, types of arrays and their applications. What is an array? An array is often a set of interrelated elements...

4 minutes read.

Java 9 Try With Resources

Java 9 provides the improvement in the try statement. It allows us to declare a try statement with duly declared resources. Whenever the user does not require the functionality with...

3 minutes read.

Enterprise Java Beans

One of the many Java APIs for the common development of corporate software is Enterprise Java Beans (EJB). An EJB, a server-side software component, contains the business logic of an...

4 minutes read.

Java Networking

Networking Networking is a way of communicating the devices. It is made up of various technologies like computers, switches, routers that are interconnected and share data among themselves. The two common network protocols: 1. TCP/IP TCP stands for...

10 minutes read.

Arithmetic Operations on String in Java

Introduction Arithmetic, Relational, Bitwise, and Logical operators are all available in Java. Simple mathematical calculations are performed using Java arithmetic operators. Basic Arithmetic operators are considered in Java to be Addition,...

4 minutes read.

Mutable class in Java

A language for object-oriented programming is Java. Because this is an object-oriented language of programming, all of its mechanisms and methods are based on objects. Java has a concept of...

6 minutes read.

Web Crawler in Java

In this article, you will be acknowledged with what a web crawler in java is and what are its functions. You will also be able to understand where to implement...

4 minutes read.

Parallel Arrays Sort in Java

Sorting is a technique of arranging a sequence of numbers in ascending order, that is, the first number being lowest and gradually incrementing the numbers such that the last number...

7 minutes read.

Java Math ulp() Method

The ulp() method of Java Math class returns the size of an ulp of the argument. Syntax: public static double ulp(double x)public static float ulp(float x) Parameters: The parameter ‘x’ represents the floating-point number...

2 minutes read.

Series Program in Java

Series Program in Java The series program in Java is written to print the mathematical series such as the Fibonacci series, Pell series, etc. A few of the renowned series are...

12 minutes read.

Replace character in string Java

Characters in Java In the package of Java language, there is a container class called Character. A single field of type char is contained in a Character object. For manipulating characters,...

4 minutes read.

Convert JSON to Map in Java

JACKSON and GSON libraries are two extremely capable JSON-related libraries offered by Java. To efficiently work with the returned JSON data, we frequently need to convert JSON responses into a...

6 minutes read.

String Concatenation in Java

In Java, it gathers a new String that combines several strings. Following are the manners to concatenate strings in Java: By + (String concatenation) operatorBy concat() method By + (String concatenation) operator Java...

4 minutes read.

Java String contains() method

contains() method returns true only if it contains the given sequence of characters otherwise it returns false. syntax: public boolean contains(CharSequence sequence) parameters: sequence : It is the sequence to be searched. Returns: It returns true...

1 minute read.

Java Enum vs Class

Enumerations are used in programming languages to represent collections of named constants. For instance, the four suits in a deck of playing cards might represent four integrators named Club, Diamond,...

7 minutes read.

if-else Program in Java

if-else Program in Java The if-else program in Java controls which code snippet will execute. The if-else program is very basic and yet very important. Because it checks how well one...

19 minutes read.

Generics in Java

Generics in Java Parameterizedtypes mean generic. Generics allow types (Character, Integer, String, …, etc., as well as user-defined types) to act as parameters to interfaces, classes, and methods. Generics in Java...

9 minutes read.

Ganesha’s Pattern in Java

This part teaches us how to use stars and other special characters to write Ganesha's Pattern in Java programming. Among the most challenging Java pattern applications to code. The Ganesha will be...

3 minutes read.