How to Read Java Console Input | 3 Ways To Read Java Input

Get Job-ready: Java Course with 45+ Real-time Projects! - Learn Java

A programmer cannot always assume what the user wants to input into the program. Most of the time it is a necessity to make the program interactive. To make the program interactive, the programmer needs to take input from the user. Java provides us with three classes using which we can take console input from the user. In this article, we will discuss all these classes one by one.

Classes provided by Java to take console Input:

There are three classes using which we can take console input:

  • BufferedReader class
  • Scanner class
  • Console class

There is also another way to take console input in Java:

  • Using Command Line Argument

Let us discuss each of these classes at length.

1. Java BufferedReader Class:

The BufferReader class is part of the java.io package. It is the oldest method introduced in Java to take user input. It has been present in Java since the very beginning. The BufferedReader class wraps the System.in(System Input) with the InputStreamReader.

Let us see how BufferedReader objects are called:

BufferedReader br= new BufferedReader(new InputStreamReader(System.in));

java bufferedreader class

BufferedReader class constructor in Java:

ConstructorDescription
BufferedReader(Reader rd)This method creates a buffered character input stream that uses the system default input buffer size.
BufferedReader(Reader rd, int size)This method creates a buffered character input stream of the specified size for an input buffer.

Methods in Java BufferedReader Class:

MethodDescription
int read()This method takes a single character input.
int read(char[] cbuf, int off, int len)This method takes characters as input and puts them into an array.
boolean markSupported()This method tests the input stream support for the mark and reset method.
String readLine()This method takes string input.
boolean ready()This method tests whether the input stream is ready to be read.
long skip(long n)This method skips a specified length of character.
void reset()This method repositions the stream at a position where the mark method was last called on this input stream.
void mark(int readAheadLimit)This method helps in marking the present position in a stream.
void close()This method helps in closing the input stream and releases any of the system resources associated with the stream.

Advantages of using BufferedReaderClass:

  • The information entered through BufferedReader class is cradled for productive perusing.

Disadvantage of Using BufferedReaderClass:

  • The code that is wrapping inside the BufferedReader Class is difficult to recall.

Code to understand BufferedReader Input:

package com.DataFlair.ConsoleInput;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class BufferedReaderInput
{
    public static void main(String[] args) throws IOException 
    {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 
        System.out.println("Enter anything: ");
        String str = br.readLine();
        System.out.println("You have Entered: ");
        System.out.println(str);        
    }
}

The output of the above code:

Enter anything:
DataFlair
You have Entered:
DataFlair

Code to take Input using java BufferedReader until the User enters any specified character:

package com.DataFlair.ConsoleInput;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class BufferedReaderInput2
{
    public static void main(String[ ] args) throws IOException 
    {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 
        String str = ""; 
        System.out.println("Enter the Strings and when you want to stop entering the Strings, type ‘.’");
        while(!str.equals("."))
        { 
            System.out.println("Enter a String: "); 
            str = br.readLine(); 
            System.out.println("The String input is: "+str); 
            if(str.contentEquals("."))
                System.out.println("FullStop!!!");
        } 
        br.close(); 
    }  
}

The output of the above code is:

Enter the Strings and when you want to stop entering the Strings, type ‘.’
Enter a String:
DataFlair
The String input is: DataFlair
Enter a String:
Java Tutorial
The String input is: Java Tutorial
Enter a String:
Console Input
The String input is: Console Input
Enter a String:
.
The String input is: .
FullStop!!!

Point to Remember:

The readLine() method only takes String input. To take inputs of other data types, we have to parse the Input in the following way:

  • Integer.parseInt(br.readLine()): To take integer value.
  • Double.parseDouble(br.readLine()): To take double value.
  • Float.parseFloat(br.readLine()): To take float value.

2. Java Scanner Class:

The Scanner class also known as the utility scanner is part of java.util package. The Scanner class is simpler and better than BufferedReader. It takes input in the console or the command line.
The Scanner class can also be used to parse strings and primitive types with the help of the Java regular expressions.
We can create a Scanner class object using the following statement:

Scanner sc = new Scanner(System.in);

Advantages of using Java Scanner class:

  • It is simple to use and is very fast.
  • It provides useful methods like nextInt(), nextDouble(), nextFloat(), etc, for parsing primitive data types from tokenized input.
  • Also it uses regular expressions which we can use to find tokens.

Disadvantage of using Java Scanner Class:

  • The methods of the scanner class are not Synchronized.

Methods present in the Java Scanner Class:

MethodDescription
int nextInt()This method is used to parse the next token of the input as an integer.
float nextFloat()This method parses the next token of the input as a float.
double nextDouble()This method is used to parse the next token of the input as a double.
byte nextByte()This method is used to parse the next token of the input as a byte.
String nextLine()This method moves the scanner past the current line.
boolean nextBoolean()This method parses the next token of the input as a boolean value.
long nextLong()This method is used to parse the next token of the input as a long.
short nextShort()This method is used to parse the next token of the input as a Short.
BigInteger nextBigInteger()This method is used to parse the next token of the input as a Big Integer.
BigDecimal nextBigDecimal()This method is used to parse the next token of the input as a Big Decimal.

Code to take user input using Scanner Class:

package com.DataFlair.ConsoleInput;
import java.util.*;
public class ScannerClassInput
{
    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a String");
        String str = sc.nextLine();
        System.out.println("The String is: " +str);
        System.out.println("Enter an Integer");
        int i = sc.nextInt();
        System.out.println("The Integer is: " +i);
        System.out.println("Enter a Float value");
        float f = sc.nextFloat();
        System.out.println("The Float value is: " +f);
    }
}

The output of the above code is:

Enter a String
DataFlair
The String is: DataFlair
Enter an Integer
21
The Integer is: 21
Enter a Float value
123.456
The Float value is: 123.456

3. Java Console Class:

Using the console class in Java we can get input from the console. The console class provides methods to take input as text or password. If we want to take password input, it will not be shown on the screen. The Console class is part of the java.io package and was introduced with the Java 1.5 update.

The declaration of console class can be given as:

public final class Console extends Object implements Flushable  

To instantiate an object of the Console class, we have to write the following:

Console c=System.console();  

Advantage of Using Java Console Class:

  • Using console class we can enter passwords without displaying them on screen.
  • The Reading methods present inside the Console class are Synchronized.
  • The Console Class lets us use the Format String Syntax.

Disadvantages of using Console Class:

  • Does not work in an IDE, only works on Command Prompt.

The methods present in the console class are:

MethodDescription
Reader reader()This method retrieves the reader object associated with the console
String readLine()This method helps in reading a single line of text from the console.
String readLine(String fmt, Object… args)This method provides a formatted prompt then reads the single line of text from the console.
char[] readPassword()This method reads a password that is not being displayed on the console.
char[] readPassword(String fmt, Object… args)This method provides a formatted prompt then reads the password that is not being displayed on the console.
Console format(String fmt, Object… args)This method helps in writing a formatted string to the console output stream.
Console printf(String format, Object… args)This method writes a string to the console output stream.
PrintWriter writer()This method helps to retrieve the PrintWriter object associated with the console.
void flush()This method flushes the console.

Code to take input using the Console class:

package com.DataFlair.ConsoleInput;
import java.io.Console; 
public class ConsoleClassInput
{ 
    public static void main(String args[])
    {    
        Console c=System.console();    
        System.out.println("Enter a String: ");    
        String Str=c.readLine();    
        System.out.println("The String is: "+Str);    
    }    
} 

The output of the above code is:

Enter a String:
DataFlair
The String is: DataFlair

Code to take password as input:

package com.DataFlair.ConsoleInput;
import java.io.*;
public class ConsolePasswordInput
{
    public static void main(String args[])
    {    
        Console c=System.console();    
        System.out.println("Enter password: ");    
        char[] passcode=c.readPassword();    
        String pass=String.valueOf(passcode);  
        System.out.println("The Password is: "+pass);    
    }    
}

The output of the above code is:

Enter password:
The Password is: DataFlair

4. Using Java Command Line Argument:

In java, we can also use the Command Line Argument to take inputs directly. If we recall the syntax of the main method, it is written as:

public static void main(String args[])

The String args lets us take input through the command line, it stores the input in the args[] array, which can be accessed inside the code.

Advantages of using Command Line Argument in Java:

  • Using Command Line Argument, we can pass any number of arguments.
  • The input in the Command Line Arguments are in String form, thus they can be converted to any data type easily.

Code to understand Command-Line Argument:

package com.DataFlair.ConsoleInput;
public class CLA
{
    public static void main(String args[])
    {
        System.out.println("The input through Command Line Argument is: ");
        for(int i=0;i<args.length;i++)
        {
            System.out.println(args[i]);
        }
    }
}

The output of the above code is:

The input through Command Line Argument is:
DataFlair

Conclusion:

In this article, we saw how to use all the three ways in which we can take console input in Java. Each of these classes has its own advantages and disadvantages. It is the duty of the programmer to decide which class they want to use in their program. Knowing how to take user input is very important, as this will help in creating an interactive program and add a better user experience.

Did we exceed your expectations?
If Yes, share your valuable feedback on Google

courses

DataFlair Team

DataFlair Team creates expert-level guides on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our goal is to empower learners with easy-to-understand content. Explore our resources for career growth and practical learning.

1 Response

  1. Rohith A says:

    i want r console output in java console

Leave a Reply

Your email address will not be published. Required fields are marked *