Read Multi-line Input from Console in Java

In this post, we will see how to read multi-line input from console using Scanner and BufferedReader class in Java.


1. Using Two Scanners

The idea is to use two scanners – one to get each line using Scanner.nextLine(), and the other one to scan through it using


Download   Run Code


2. Using Single Scanner

We can even read each line with single scanner. The idea is to read each line using Scanner.nextLine() method and use String.split() or StringTokenizer to read tokens from each line.


Download   Run Code


Here’s another version where only is used:


Download   Run Code


3. BufferedReader Class

Another way to read multiple lines from console can be done using synchronized BufferedReader class in Java. The idea is to read each line using readLine() method and use String.split() to split the line into individual tokens using whitespace as delimiter. We can also use StringTokenizer class.


Download   Run Code

From Java 7 onward, we should use try-with resources as shown below:


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