Javatpoint Logo
Javatpoint Logo

How to take Character Input in Java using BufferedReader Class

In Java, the Scanner class is used to take character input from the user. The Scanner class is not a single solution of taking character input from the user. The BufferedReader class an alternative to the Scanner class for taking character input from the user. Let's start understanding how to take character input in Java using BufferedReader.

These are the following steps to take character input using BufferedReader:

How to take Character Input in Java using BufferedReader Class
  1. In the first step, we have to create an instance of the BufferedReader class by using the InputStreamReader The InputStreamReader is a class that act as a bridge in between the byte stream to character stream. The reason of using InputStreamReaderis to decode bytes to characters.
  2. We will use the read() method of the BufferedReader class to read character from the given BufferedReader and typecast it to char.
  3. We will store the return value of the read() method into the character type variable. The read() method returns the character read by this method. The read() method gives us result -1 in case when the buffered stream has ended and there is no character to be read.
  4. At the end, we will print the character data on the screen which we read using the read() method.

Let's take some example to understand how the BufferedReader class is used to read character data in Java.

We will take two examples, i.e., BufferedReaderExample and BufferedReaderExample2. In the first example, we will simply read the character data using the BufferedReader class and print it to the screen. In the second example, we will get the string from user using BufferedReader class and perform some operations on the user entered string.

BufferedReaderExample.java

Output

How to take Character Input in Java using BufferedReader Class

BufferedReader class can also be used to get the string from the user. For this, we will use the readLine() of the BufferedReader class. Let's understand it by taking another example of BufferedReader. We will calculate the area of the triangle by taking its base value and height value from the user as a string using BufferedReader class. We then convert the string data into a double by parsing string data, and then we calculate the area of the triangle by using the formula (base*height)/2.

BufferedReaderExample2.java

Output

How to take Character Input in Java using BufferedReader Class




Youtube For Videos Join Our Youtube Channel: Join Now

Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA