This post will discuss how to read a string from standard input (System.in) using Scanner and BufferedReader in Java. Since a single line of input may contain multiple values, split the line into string tokens.

1. Using Scanner

A simple solution is to use the Scanner class for reading a line from System.in. A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.

Download Code

 
We can also use StringTokenizer with the Scanner in place of String.split() to split the input as StringTokenizer is much faster.

Download Code

 
We can also use the Scanner.next() method to convert the resulting tokens into string values, as shown below. Here, hasNext() returns true if this scanner has another token left.

Download Code

2. Using BufferedReader

Although Scanner is very convenient for parsing the input, we can speed up things a little by using the BufferedReader and StringTokenizer combo in Java, which is much faster than the Scanner.

In the following program, readLine() reads a line of text which is terminated by any one of a carriage return ('\r'), line feed ('\n'), or a '\r\n'.

Download Code

That’s all about reading a string from standard input in Java.