How to take user input in java

All interactive applications have one thing in common…. Interaction with end user. An application can easily send its output to the user by printing on console (monitor) but how will an application take input from the user.
This post will explain different methods to read user input from the console.

Concept
Java provides a stream connected to the keyboard via a static field in java.lang.Systemclass. This field is named in.
Thus, calling System.ingives you access to the input stream connected to the keyboard. Most of the methods of reading input from keyboard utilize this input stream.
From java docs, the description of field inof java.lang.Systemclass states :

The “standard” input stream. This stream is already open and ready to supply input data. Typically this stream corresponds to keyboard input or another input source specified by the host environment or user.

How to read user input
Below listed methods demonstrate how to read user input supplied from keyboard.

Method 1 : Using BufferedReader class
java.io.BufferedReader provides buffering which adds support for reading a string or an entire line of input. This means that user is able to enter words separated by spaces as well.
java.io.BufferedReaderhas a constructor which takes a java.io.Readeras argument. Hence we pass it an object of java.io.InputStreamReaderwhich is a subclass of java.io.Reader.
java.io.InputStreamReader accepts an input stream as argument, thus we pass it the input stream connected to the keyboard which we can easily get through System.in.
Example program to read input using a BufferedReader is given below.

	static void usingBufferedReader() throws IOException {
		BufferedReader br = null;
		System.out.println("Enter a random text");
		try {
                        br = new BufferedReader(new InputStreamReader(
                                    System.in));
			String input = br.readLine();
			System.out.println("User Input is : " + input);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (br != null) {
			   br.close();
			}
		}
	}

Output :

Enter a random text
coDippa
User Input is : coDippa

Method 2 : Input using Scanner class
java.io.Scannerclass can be used to take input from the user. It has a constructor that accepts an object of input stream as its source.
Since we want our input to come from keyboard, we pass it the input stream connected to the keyboard which is System.in.
java.io.Scannerclass has various methods for reading input based on its type such as nextInt(), nextDouble(), nextBoolean(). Thus, the scanner can be used to read a string, a character, a double, an integer or a boolean value as input.
For reading a string or an entire line of text using scanner, we need to use its nextLine()method.

static void usingScanner() {
   Scanner scanner = null;
   try {
	System.out.println("Enter a random text");
	scanner = new Scanner(System.in);
	String input = scanner.nextLine();
	System.out.println("User Input is : " + input);
   } catch (Exception e) {
	e.printStackTrace();
   } finally {
	if (scanner != null) {
           scanner.close();
	}
   }
}

Output :

Enter a random text
coDippa
User Input is : coDippa

Method 3 : Input using Console
java.io.Consoleclass represents the character based console and provides methods to read from and write to the console.
Instance of java.io.Consoleclass can be retrieved by calling static console()method of java.io.Systemclass. java.io.Consoleclass provides a method called readLine()which reads an entire line from the console.
A limitation using this method is that it can only be used when running application on the command prompt which means this method will not work on an IDE. If a console instance is not available, System.console()returns null. Therefore, a null check should be done before performing any IO operations on console.

static void usingConsole() {
   Console console = System.console();
   if (console != null) {
	System.out.println("Enter a random text");
	String input = console.readLine();
	System.out.println("User Input is : " + input);
   } else {
	System.out.println("No console available");
   }
}

Output

Enter a random text
coDippa
User Input is : coDippa

Let’s tweak in

  1. All methods requiring keyboard input require interaction with java.io.InputStream supplied by java.lang.System class. This input stream is provided by calling System.in.
  2. java.io.Console class can be used to read secured text without echoing it back on screen such as passwords, account, credit card numbers etc. using its readPassword() method.
  3. System.console()method returns the command prompt terminal instance if it finds one otherwise null. Hence, method 3 will only work when executed through command prompt.
  4. If you want to specifically read integers in user input, then use java.io.Scanner‘s nextInt()method.
  5. When trying to read a specific type of input using java.io.Scanner, the input entered should be convertible to that type.
    For Example, when trying to read an integer using readInt()method, the input entered should be convertible to an integer. If the user enters “23da“, then java.util.InputMismatchException will be thrown.
  6. If you are writing and testing your program in an IDE (such as eclipse or NetBeans), then use either Method 1 or 2. Method 2 will not work in IDE.

If there are some other ways, which you are familiar with, let others know.

Hit the clap!!!

0

Share your thoughts !!

Close Menu

Never Miss an article !

Get the new post delivered straight into your inbox, enter your email and hit the button

You have successfully subscribed to the newsletter

There was an error while trying to send your request. Please try again.

codippa will use the information you provide on this form to be in touch with you and to provide updates and marketing.