Reading Inputs in Java

Nima Karimian Kakolaki
4 min readJul 6, 2024

--

Reading inputs in Java is a little bit more complicated than for example in python. If you’re familiar enough with python you know that we can read inputs like this :

user_name = input("enter your username here: ")

Reading From InputStream

The scenario is completely different in java. To be able to read input from Standard Input Stream in java we first have to create a Scanner. Scanner in java simplifies the process of reading inputs, it gives us bunch of useful methods and with these methods we can break users input into smaller pieces of data and also we can convert these smaller pieces into usable formats. namely,

  • Numbers (int,float,long,etc.)
  • Boolean (false, true)
  • String
Scanner in = new Scanner(System.in);

As you can see in the code above, we constructed a scanner object and binded it with the “System.in”. The Scanner class provides various methods to read different types of data entered by the user. Here are some common methods:

  • nextLine(): Reads an entire line of text entered by the user (including spaces).
  • nextInt(): Reads the next integer value entered by the user.
  • nextDouble(): Reads the next double-precision floating-point value.
  • nextBoolean(): Reads the next boolean value (true or false) entered by the user.

Java Scanner in Details

First we need to construct a new Scanner Object Variable

Scanner input = new Scanner(System.in);

Constructs a new Scanner that produces values scanned from the specified input stream. Bytes from the stream are converted into characters using the default charset. — Java Doc

Reading String input

Scanner.nextLine() reads the next line of input.

String firstName = input.nextLine();
String lastName = input.nextLine();

This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line. — Java Doc

Warning:

Since this method continues to search through the input looking for a line separator, it may buffer all of the input searching for the line to skip if no line separators are present.

ForExample, If you use the nextLine() method immediately following the nextInt() method, recall that nextInt() reads integer tokens; because of this, the last newline character for that line of integer input is still queued in the input buffer and the next nextLine() will be reading the remainder of the integer line (which is empty).

Reading Numbers Input

Fortunately we can directly read inputs from InputStream in Java without the hassle of TypeCastings and Conversions. Since, we can read the input as a type that we desire.

int age = input.nextInt(); //int
float weight = input.nextFloat(); // float
long bankAccount = input.nextLong(); //Long Int
double bankBalance = input.nextDouble(); //double floating precision

Warning:

As we said earlier, make sure to use nextLine() method after reading number inputs in java if you intend to read lines after them.

long bankAccount = input.nextLong(); //Long Int
input.nextLine();
String bankName = input.nextLine();

Reading Boolean Values

You are also able to read boolean values from InputStreams in Java

boolean isActive = input.nextBoolean();

Close the Scanner

input.close();

It’s good programming practice to close the Scanner after reading input from InputStreams. Since, Scanner utilizes system resources like the underlying input stream (System.in). Closing the scanner explicitly releases these resources, allowing other parts of your program or the system itself to use them if needed. If you don’t close the scanner, it can lead to a resource leak. This means the resources allocated to the scanner remain occupied even though you’re not using them anymore

Reading Password

One thing you need to pay attention to, is that you should not use Scanner to read passwords from the client since, input is visible to anyone. If you intend to read Passwords from Input you should consider using the Console Class.

Console Class

        Console console = System.console();
char[] pass = console.readPassword("Enter a Password");
System.out.println(pass);

For Security purposes password is returned as an array. make sure to empty the array after processing the password you have just read or replace the password array with filler values. one thing to keep in mind is that, System.console() is not always available and you should handle the situation if it returns null.

Photo by Andras Vas on Unsplash

Make sure to check my articles about Java — Spring for more interesting facts and knowledges.

Related articles:

--

--

Nima Karimian Kakolaki

Software engineer student with focus on information systems and machine learning.