Java

Read String from Console in Java

We can use below classes to read input from console.

1. BufferedReader
2. Scanner

Java Read String from Console using BufferedReader

BufferedReader class is from Java IO package. We can use BufferedReader to read text from a character-input stream.

Output:

Java Read from Console using Scanner

If you notice above code, BufferedReader is not flexible and has very limited options. We can only read input data as String. That’s why Scanner class was introduced in Java 1.5 to read from console with many options.

We can use Scanner class to read as String, primitive data types such as int, long etc. We can also read input numbers in different bases such as binary and read it to integer. Let’s have a look at how to use Scanner class to read input data from console.

 

Output:

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.