The Wayback Machine - https://web.archive.org/web/20240601053843/https://www.geeksforgeeks.org/ways-to-read-input-from-console-in-java/
Open In App

Ways to read input from console in Java

Last Updated : 12 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In Java, there are four different ways to read input from the user in the command line environment(console). 

1. Using Buffered Reader Class

This is the Java classical method to take input, Introduced in JDK1.0. This method is used by wrapping the System.in (standard input stream) in an InputStreamReader which is wrapped in a BufferedReader, we can read input from the user in the command line. 

  • The input is buffered for efficient reading.
  • The wrapping code is hard to remember.

Implementation:

Java
// Java program to demonstrate BufferedReader
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Test {
    public static void main(String[] args)
        throws IOException
    {
        // Enter data using BufferReader
        BufferedReader reader = new BufferedReader(
            new InputStreamReader(System.in));

        // Reading data using readLine
        String name = reader.readLine();

        // Printing the read line
        System.out.println(name);
    }
}

Input: 

Geek

Output: 

Geek

Auxiliary Space: O(1) 

Note: To read other types, we use functions like Integer.parseInt(), Double.parseDouble(). To read multiple values, we use split().

2. Using Scanner Class

This is probably the most preferred method to take input. The main purpose of the Scanner class is to parse primitive types and strings using regular expressions; however, it is also can be used to read input from the user in the command line. 

  • Convenient methods for parsing primitives (nextInt(), nextFloat(), â€Ķ) from the tokenized input.
  • Regular expressions can be used to find tokens.
  • The reading methods are not synchronized.

To see more differences, please see this article.

Java
// Java program to demonstrate working of Scanner in Java
import java.util.Scanner;

class GetInputFromUser {
    public static void main(String args[])
    {
        // Using Scanner for Getting Input from User
        Scanner in = new Scanner(System.in);

        String s = in.nextLine();
        System.out.println("You entered string " + s);

        int a = in.nextInt();
        System.out.println("You entered integer " + a);

        float b = in.nextFloat();
        System.out.println("You entered float " + b);
    }
}

Input: 

GeeksforGeeks
12
3.4

Output:

You entered string GeeksforGeeks
You entered integer 12
You entered float 3.4

3. Using Console Class

It has been becoming a preferred way for reading user’s input from the command line. In addition, it can be used for reading password-like input without echoing the characters entered by the user; the format string syntax can also be used (like System.out.printf()). 

Advantages:

  • Reading password without echoing the entered characters.
  • Reading methods are synchronized.
  • Format string syntax can be used.
  • Does not work in non-interactive environment (such as in an IDE).
Java
// Java program to demonstrate working of System.console()
// Note that this program does not work on IDEs as
// System.console() may require console
public class Sample {
    public static void main(String[] args)
    {
        // Using Console to input data from user
        String name = System.console().readLine();

        System.out.println("You entered string " + name);
    }
}

Input: 

GeeksforGeeks

Output:

You entered string GeeksforGeeks

4. Using Command line argument

Most used user input for competitive coding. The command-line arguments are stored in the String format. The parseInt method of the Integer class converts string argument into Integer. Similarly, for float and others during execution. The usage of args[] comes into existence in this input form. The passing of information takes place during the program run. The command line is given to args[]. These programs have to be run on cmd.

Code Implementation:

Java
// Program to check for command line arguments
class Hello {
    public static void main(String[] args)
    {
        // check if length of args array is
        // greater than 0
        if (args.length > 0) {
            System.out.println(
                "The command line arguments are:");

            // iterating the args array and printing
            // the command line arguments
            for (String val : args)
                System.out.println(val);
        }
        else
            System.out.println("No command line "
                               + "arguments found.");
    }
}

Command Line Arguments: 

javac GFG1.java
java Main Hello World

Output:

The command line arguments are:
Hello
World

5. Using DataInputStream class

A DataInputStream in Java is a class that provides a convenient way to read primitive Java data types from an input stream in a machine-independent manner. It wraps an existing InputStream and allows applications to read Java primitive data types (int, short, long, byte, float, double, char, boolean) and strings from the underlying input stream, preserving their binary format. DataInputStream is part of the java.io package and is particularly useful when you need to read data that was written using a DataOutputStream or any other source that wrote data in a compatible format.

Definition:

DataInputStream is a Java class that implements data input operations. It allows applications to read primitive data types and strings from an input stream in a machine-independent way. It achieves this by wrapping an existing input stream and providing methods to read various primitive data types and strings from the underlying input source.

Remember that DataInputStream reads data in a binary format, so it’s important to ensure that the data being read was written using the correct methods in DataOutputStream or a compatible source to avoid data corruption or misinterpretation.

Code Implementation:

Java
//Java program to read input using DataInputStream class
import java.io.*;

public class Main {
    public static void main(String[] args) throws IOException {
        DataInputStream reader = new DataInputStream(System.in);
        
        // Reading integers
        System.out.print("Enter an integer: ");
        int inputInt = Integer.parseInt(reader.readLine());
        
        // Reading strings
        System.out.print("Enter a string: ");
        String inputString = reader.readLine();
        System.out.println("You entered integer: " + inputInt);
        System.out.println("You entered string: " + inputString);
        
    }
}

Input:

Enter an integer: 10
Enter a string: GeeksForGeeks

Output:

You entered integer: 10
You entered string :GeeksForGeeks

Please refer this for more faster ways of reading input.



Previous Article
Next Article

Similar Reads

Java Multithreading - One Thread to Take Input, Another to Print on Console
Multithreading is a concept in which our program can do two or more tasks at the same time. Thread is the execution unit of any process. Every process has at least one thread which is called main thread. In this article, we will create a Java program that will do printing on the console until the user gives input. Here, we need two threads. One thr
4 min read
Taking input from console in Python
What is Console in Python? Console (also called Shell) is basically a command line interpreter that takes input from the user i.e one command at a time and interprets it. If it is error free then it runs the command and gives required output otherwise shows the error message. A Python Console looks like this. Here we write a command and to execute
2 min read
Java.io.Console class in Java
The Java.io.Console class provides methods to access the character-based console device, if any, associated with the current Java virtual machine. The Console class was added to java.io by JDK 6. Important Points: It is used to read from and write to the console, if one exists. Console is primarily a convenience class because most of its functional
4 min read
Console printf(String, Object) method in Java with Examples
The printf(String, Object) method of Console class in Java is used to write a formatted string to the output stream of the console. It uses the specified format string and arguments. It is a convenience method. Syntax: public Console printf(String fmt, Object... args) Parameters: This method accepts two parameters: fmt - It represents the format of
2 min read
Console readPassword() method in Java with Examples
The readPassword() method of Console class in Java is of two types: 1. The readPassword() method of Console class in Java is used to read a password or passphrase from the console with disabled echoing. Syntax: public char[] readPassword() Parameters: This method does not accept any parameter. Return value: This method returns a character array tha
4 min read
Console flush() method in Java with Examples
The flush() method of Console class in Java is used to flush the console and to force any buffered output to be written immediately. Syntax: public void flush() Specified By: This method is specified by flush() method of Flushable interface. Parameters: This method does not accept any parameter. Return value: This method does not return any value.
2 min read
Console reader() method in Java with Examples
The reader() method of Console class in Java is used to retrieve the unique Reader object which is associated with the console. This reader() method is generally used by sophisticated applications. Simple applications that require only line oriented reading, normally use readLine() method instead of reader() method. Syntax: public Reader reader() P
2 min read
Console format(String, Object) method in Java with Examples
The format(String, Object) method of Console class in Java is used to write a formatted string to the output stream of the console. It uses the specified format string and arguments. Syntax: public Console format(String fmt, Object... args) Parameters: This method accepts two parameters: fmt - It represents the format of the string. args - It repre
2 min read
Console writer() method in Java with Examples
The writer() method of Console class in Java is used to retrieves the unique PrintWriter object which is associated with the console. Syntax: public PrintWriter writer() Parameters: This method does not accept any parameter. Return value: This method returns the PrintWriter which is associated with the console. Exceptions: This method does not any
1 min read
Console readLine() method in Java with Examples
The readLine() method of Console class in Java is of two types: 1. The readLine() method of Console class in Java is used to read a single line of text from the console. Syntax: public String readLine() Parameters: This method does not accept any parameter. Return value: This method returns the string containing the line that is read from the conso
3 min read
Practice Tags :