1. Home
  2. >
  3. Java
  4. >
  5. How to Take Input...

How to take input in Java

How to Take Input From User in Java

Java claims that it is used on 3 billion devices all round the globe and hence to fulfill all the user’s demand it provides all the necessary means required to take input of any form.

Our major focus in this article will be to dwell upon the inputs we can take from the keyboard. This mostly covers the primitive data types, files etc.

4 Ways to take input from user in Java

  • Using Buffered Reader Class
  • Using Scanner Class
  • Using Console Class
  • Using File Handling

An integral part of a program is to take inputs from its user.

What is an input?

In computer science, an input refers to something that is provided to the computer. These inputs are provided by many input devices. A few of them are:

  • Keyboard
  • Touchscreen
  • Touchpad

What are these inputs?

Command Line arguments

  • In order to run our program we need to provide the instructions through the command line. These commands allow the JVM to recognise the program which it needs to compile into a byte file and later run for execution.
  • Commands
compile by > javac CommandLineExample.java  
run by > java CommandLineExample

Keyboard interactions

  • Wired and wireless keyboards provide us the linguistic inputs in form of commands 

Files in the system

  • For systemised storage of all interrelated data we all choose file storage. These files are stored under various directories. In order to manipulate these files for any CRUD operations we need to first specify their paths and import them in our programs.
import java.io.File;  // Import the File class
File myObj = new File("filename.txt"); // Specify the filename
import java.util.*;
import java.io.File; //for file handling
import java.io.FileNotFoundException; //for catching file exception
 
public class fileHandling{
    public static void main(String[] args) {
        try {
        //creating an object of the file and initialising with the file address
        File myObj = new File("C:/Files/demo.txt");  
        Scanner myReader = new Scanner(myObj);
        while (myReader.hasNextLine()) {
            //printing whenever a line existsin file
            String data = myReader.nextLine();
            System.out.println(data);
        }
        myReader.close();
        } 
        catch (FileNotFoundException e) {
            System.out.println("An error occurred.");
            e.printStackTrace();
        }
    }
};

Output:

HELLO WORLD
THIS IS THE DEMO FILE FOR SHOWING FILE HANDLING IN JAVA

Using Buffered Reader Class

Take input in Java using buffered class

This is the most primitive method offered by Java for taking user inputs. The name tells about its main function, which is to provide a buffer for data. This buffer stores the input given by the user which is transferred through the input stream.

It wraps the System.in in InputStreamReader which is later wrapped under bufferReader.

It can also read input from users through the command line as well.

Syntax:

BufferedReader bufferVariable = new 
BufferedReader(newInputStreamReader(System.in));

Code:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
 
public class bufferedReader {
   public static void main(String[] args) throws IOException {
       InputStreamReader input = new InputStreamReader(System.in);
       BufferedReader reader = new BufferedReader(input);
 
       System.out.println("Please enter the input:");
       String name = reader.readLine();
       System.out.println("You entered: ");
       System.out.println(name);
   }
}

Output:

HELLO WORLD
THIS IS THE DEMO FILE FOR SHOWING FILE HANDLING IN JAVA

Advantages

  1. It is the most efficient method for reading input
  2. It works better when we read files because of its large buffer size
  3. We can use it while working on multiple threads
  4. There is no ambiguity related to nextline() method

It is observed that when nextLine() method is used after any next….() method, the program fails to input a string using nextLine() method.

This is because nextLine() takes a line change character ‘/n’ as an input and we are shown an empty string. 

Disadvantages

  1. It needs the InputStreamReader function
  2. We may need to specify the buffer size even though the default size is itself very large
  3. It can only take string inputs. For other data types we need specific parse functions
  4. We need to add multiple libraries into our program
    • import java.io.BufferedReader;
    • import java.io.IOException;
    • import java.io.InputStreamReader;

Using Scanner Class

This is the most widely used method for taking inputs in a java program. It implements the ‘Scanner’ class which provides us specific methods to parse the input given to the program using specific methods listed below.

Taking input in Java using Scanner Class

Syntax

Scanner scannerVariable = new Scanner(System.in);

This statement invokes a constructor of class Scanner and the argument ‘System.in’ specifies that we will be focusing on keyboard input using standard input stream.

Code:

import java.util.Scanner;
 
public class scannerInput {
   public static void main(String[] args) {
       Scanner sc=new Scanner(System.in);
       System.out.println("Enter an integer");
       int a=sc.nextInt();
       System.out.println("Enter a string");
       String s=sc.nextLine();
       System.out.println("String is "+ s);
   }
}

Output:

Enter the input
Scaler.com
You Entered Scaler.com

Process finished with exit code 0

Advantages

  1. It is easy to implement and hence it is widely used
  2. It is more compatible for smaller data types and it is generally the best option for competitive coding
  3. Provide convenient methods for parsing the primitive data types which are easy to memorise (ex. nextInt(), nextFloat(), …) from the tokenized input
Scanner Method for Taking Input in Java
  1. Regular expressions can be used to find tokens.Reading methods are not synchronized
  2. It offers a much easier approach to read records from a data file.
  3. We do not need to mention any InputStreamReader

Disadvantages

  1. It is slower as compared to the buffered reader
  2. It fails to perform efficiently for larger inputs as its buffer size is (1KB char buffer)which is very small when compared to bufferreader’s (8KB byte buffer).
  3. It is not synchronous and it does not deliver appropriate performance when we work with multiple threads.
  4. There are a lot of problems with the nextline() method.

Using Console Class

This method is usually used for inputting passwords. In addition, it can be used for reading password-like input without echoing the characters entered by the user. The format of the input string syntax can also be used (like System.out.printf()).

We need to add the java.io.Console library to implement the System.Console() function.

Syntax

Console c=System.console();

Code:

import java.io.Console;
 
public class consoleInput {
   public static void main(String[] args) {
       Console c=System.console();
       System.out.println("Enter your name: ");
       String n=c.readLine();
       System.out.println("Welcome "+n);
   }
}

Output:

Enter the password

Entered password is Scaler

Advantages

  1. It allows us to enter passwords to our system with security as it does not make the password visible while typing it
  2. We can use the format of strings to specify the input strings format
  3. The method used by this class is synchronized

Disadvantages

  1. This method fails to work in interactive environments like IDEs where all the input is not given at once. This does not allow us to utilise shortcuts offered by popular compilers like Visual Studio Code and IntelliJ

Command Line Inputs

We can provide inputs to our program through the command prompt just the moment after we begin to execute our program.

Java programs are compiled and run by 

Compile > javac filename.java 

Run > java filename

These inputs are to be added just after the filename in the run command.

These inputs are dealt by JVM(Java Virtual Machine). They are taken as strings and passed to the main function parameter.

For short inputs we do not face any issue in entering them manually. But entering large inputs can be a tedious job for a user. For such large inputs we have third-party libraries like Picocli and Spring Shell

Key points

  • These inputs are easy to access and modify just like normal arrays
  • These inputs enable us to configure our program accordingly so that we can run our program differently every time and test it more accurately
  • The inputs that we give to the program are read as strings by the JVM(Java Virtual Machine) and wrapped under the main function parameter
  • There is no restriction to number of inputs being given

Code:

public class cmdArgs{
    public static void main(String[] args){
        System.out.println("The number of command line inputs entered are "+args.length);
        System.out.println("The inputs are as follows");
        for(int i=0;i<args.length;i++){
            System.out.println("input "+(i+1)+" is "+args[i]);
        }
        args[1]="this input was changes"; //changing value
        System.out.println("Inputs after modification are");
        for(int i=0;i<args.length;i++){
            System.out.println("input "+(i+1)+" is "+args[i]);
        }
    }
}

Output:

The number of command line inputs are 6 
The inputs are as follows 
input 1 is 1 
input 2 is a 
input 3 is black 
input 4 is 98765 
input 5 is \$%^
input 6 is !@ 
Inputs after modification are
input 1 is 1 
input 2 is this input was changes 
input 3 is black 
input 4 is 98765 
input 5 is \$%^ 
input 6 is !@

Conclusion

Hence Java allows its users to build interactive user friendly, secure, robust and memory efficient softwares and applications by providing numerous methods and libraries. 

The language is platform-independent and provides methods to input various data types. These features make it more attractive to users. In addition to this the versatile nature of Java, its simple syntax and huge community enables any developer to learn it and implement it without much difficulty.

+ posts