Java Input Example
This article will feature an example of Java User Input. The Scanner class in the java.util package is used to get user input.
We will look into various ways of obtaining user input in Java with relevant code examples.
1. Introduction
User Input refers to the data that is sent to computer application for processing using an input device like keyboard. Computer application receives the keyboard device input in the form of an input stream which is a flowing sequence of data that can be directed to specific functions for processing
2. Java Input
In Java, User Input from keyboard is available to be read as an input stream through java.lang.System
class which encapsulates standard input and standard output. It is part of Java Development Kit since version 1.1
2.1 What is System.in ?
java.lang.System.in
denotes the standard input byte stream corresponding to user keyboard input. It is automatically connected to the keyboard reading mechanism of operating system. The stream is already open in a running java application ready to supply user input data from keyboard.
2.2 User Input in Java
User Input data from the standard input stream can be read and processed using various library classes provided by java development kit so as to make the input available to the Java application and the library classes are listed below
java.util.Scanner
java.io.BufferedReader
java.io.Console
Let us understand how to read user input using the above library classes with code examples in the sections that follow.
2.3 Reading User Input using Scanner
The Scanner class in the java.util package is used to get user input. Scanner is a simple text reader that can parse primitive types and strings using regular expressions. It has been added to JDK 1.5.
It breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods.
Scanner in Java is instantiated using the standard input stream like below:
Scanner scan = new Scanner(System.in);
Below code demonstrates on how to read line input in Scanner using its nextLine()
method
Scanner in = new Scanner(System.in); // Scanner instantiation System.out.println(in.nextLine()); // Reads user input line
One of the main advantages of Scanner is that it provides various methods such as next(), nextInt(), nextDouble(), nextByte(), nextBoolean(), nextShort(), nextFloat(), nextBoolean() to parse user input into primitive types.
The below example demonstrates on how to read primitive input types using various methods of Scanner
UserInputWithScanner
public class UserInputWithScanner { public static void main(String[] args) { System.out.println("Enter your details"); Scanner in = new Scanner(System.in); // Scanner instantiation System.out.print("Name : "); String name = in.next(); // Scanner method to read complete text System.out.println("Name : " + name); System.out.print("Age : "); int i = in.nextInt(); // Parses input as a primitive integer System.out.println("Age : " + i); System.out.print("Salary : "); double d = in.nextDouble(); // Parses input as a primitive double System.out.println("Salary :: " + d); System.out.print("Married : "); boolean isMarried = in.nextBoolean(); // Parses input character as a primitive boolean System.out.println("Married : " + isMarried); in.close(); // Closes underlying standard input stream } }
The above code when executed produces the output as shown in the image of the console below and it can be seen that Scanner parses the primitive type input appropriately when using its next methods
It is important to note that when an incorrect input type is passed against the next method corresponding to a primitive type, Scanner throws java.util.InputMismatchException
and the exception is clearly illustrated in the below image of the console output
2.4 Reading User Input using BufferedReader
BufferedReader is as well a text reader to read text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines. The buffer size may be specified, or the default size (8 KB) may be used. It has been added as part of Java 1.1
BufferedReader is instantiated with underlying InputStreamReader which reads the input data in the form of bytes from keyboard using System.in
and decodes them into characters thus enabling BufferedReader for efficient reading of characters, arrays, and lines.
Below is the code snippet to instantiate BufferedReader
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
Unlike Scanner, BufferedReader provides methods only to read lines or a single character from the input and so input lines read as a String need to be parsed to the corresponding primitive data types. This has been illustrated in the below example where input fields are read as a String and parsed to various primitive types using parse methods available in respective boxed classes
UserInputUsingBufferedReader
public class UserInputUsingBufferedReader { public static void main(String[] args) { System.out.println("Enter your details"); BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(System.in)); // Instantiation System.out.print("Name : "); String name = reader.readLine(); // Reads complete input token as String System.out.println("Name : " + name); System.out.print("Age : "); int i = Integer.parseInt(reader.readLine()); // Parses string input as a primitive integer System.out.println("Age : " + i); System.out.print("Salary : "); double d = Double.parseDouble(reader.readLine()); // Parses string input as a primitive double System.out.println("Salary :: " + d); System.out.print("Married : "); boolean isMarried = Boolean.parseBoolean(reader.readLine()); // Parses string input character as a primitive boolean System.out.println("Married : " + isMarried); } catch (Exception ex) { ex.printStackTrace(); } finally { try { reader.close(); // Closes standard input stream in the underlying InputStreamReader } catch (IOException e) { } } } }
The above code when executed produces the output printing the given input field values as shown in the console image below
One important thing to note is that when an invalid string type is provided against a certain numerical primitive type, java.lang.NumberFormatException
is encountered as shown in the console output image below denoting the error while parsing the input text into number
2.2 Reading user input using Console
Java Console class provides methods to read text and password. The main reason to use Console class to read password is because echoing of the input text entered for password is disabled thus making it more secure
Console is obtained from System class like below
Console c = System.console();
Below is the code to read input using Console class
UserInputUsingConsole
package com.javacodegeeks.examples; import java.io.Console; public class UserInputUsingConsole { public static void main(String[] args) { System.out.println("Enter account details"); Console c = System.console(); System.out.print("Enter user name : "); String name = c.readLine(); // Reads input line from console System.out.println("User name : " + name); System.out.print("Enter password : "); char[] password = c.readPassword(); // Reads password without echoing the input to the console System.out.println("Password : " + new String(password)); } }
It is important to note the above code throws java.lang.NullPointerException
when executed from IDE as IDEs do not use the actual console and runs your application as a background process.
When the above code is executed from the console, it produces the output like below:
Enter account details Enter user name : UserA User name : UserA Enter password : Password : 1234
As stated earlier, we can observe that the entered password is not echoed to the console screen
3. Summary
In the article, we have understood with examples on various techniques to read user input in Java. Among the three techniques, the most widely used one to read user input in Java is using Scanner because of its simplicity, easy implementation and the powerful utility to parse text into primitive data.
4. Download the Source Code
This source contains the example code snippets used in this article to illustrate the Java Input Example.
You can download the full source code of this example here: Java User Input Example