Read Data From Console in Java

In the tutorials we will see, How can we read data from the console in Java.

There are many ways to read data from the keyboard. For example:

  • InputStreamReader
  • Console
  • Scanner

Java InputStreamReader class can be used to read data from the keyboard. It converts the byte-oriented stream into the character-oriented stream. We have already seen BufferedReader is InputStreamReader type.

 

Read Data from Console

BufferedReader Class in Java

BufferedReader class can be used to read data.  BufferedReader read the data line by line. To read the data using BufferedReader we use readLine() method of the BufferedReader class.

Let’s see an example, we are connecting the BufferedReader stream with the InputStreamReader stream for reading the line by line data from the keyboard.

 

You can copy paste and run the above code on your local machine. If you are using this code using cmd or Linux terminal then run the above file and enter the desired text and press enter once more to verify the result.

If you are using eclipse IDE to run the above code then run the class file, switch to eclipse console and enter the text and press enter. This will print your entered line.

Using this we can read the data from keyboard or console using BufferedReader class.

 

Read Data Using Scanner Class in Java

The Scanner class in Java is used for taking input from the user. The Scanner class can take an input of all the data types. The scanner can split the input after every whitespace.

It provides many methods to read and parse various primitive values.

Java Scanner class is widely used to parse text for string and primitive types using the regular expression.\

 

Methods in Scanner Class – There are many methods in the Scanner class. Let’s see some of the important methods –

  • public String next() – It returns the next token from the scanner.
  • public String nextLine() – It moves the scanner position to the next line and returns the value as a string.
  • public int nextInt() – It scans the next token as an int value.
  • public long nextLong() – It scans the next token as a long value.
  • public float nextFloat() – it scans the next token as a float value.

 

Let’s take an example, to get input from console –

You can try the above code in your local as well. Once you will run the above code it will ask to enter the number – Enter the desired number in the console and press enter then it will ask to enter string – Enter string and press enter then it will ask to enter the double value. Enter the double value and press enter.

Now program will print all the values, you entered in the console.

So that’s all, how can we entered the values on the console and we can read these console values.

0 Comment

Leave a Reply