Java : Reading Input

Reading an input, can be done in two ways,

1. Using a buffered reader
2. Using a JOptionPane

I Prefer the second.

Using buffered reader:


First create a InputStreamReader for the object

InputStreamReader fis = new InputStreamReader(;

Then create a buffered reader for fis object,

BufferedReader br = new BufferedReader(fis);

now use the readLine() method of BufferedReader to read input which returns a string.

String input = br.readLine();

Using JOptionPane:

Use the swing package.

import javax.swing.JOptionPane;

now use the showInputDialog() method to get the input.

String input = JOptionPane.showInputDialog(“Enter your name:”);

The string passed inside the InputDialog will be shown on a DialogBox and a text field is give to enter the input.

The value should be collected into a string. And parsed to it’s respective type.

For example, assume I want to get the age of a person, so,

String input = JOptionPane.showInputDialog(“Enter your age:”);

int age = Integer.parseInt(input);

The string value is converted to an integer value using the parseInt() method available in Integer class.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s