Read a String from Standard Input in Java

In this post, we will see 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. Scanner

Simple solution is to use 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   Run Code

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

 

Download   Run Code

 
We can also use 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   Run Code

 

2. BufferedReader

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

In below 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   Run Code

 

 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz