Important alert: (current site time 7/15/2013 12:50:16 PM EDT)
 

article

EASY way to understand java INPUT and OUTPUT Streams

Email
Submitted on: 5/17/2005 10:19:26 AM
By: Raghu Ram  
Level: Beginner
User Rating: By 13 Users
Compatibility: JavaScript
Views: 7197
author picture
(About the author)
 
     In Java, a source of input data is called an input stream and the output data is called an output stream.


 
 
Terms of Agreement:   
By using this article, you agree to the following terms...   
  1. You may use this article in your own programs (and may compile it into a program and distribute it in compiled format for languages that allow it) freely and with no charge.
  2. You MAY NOT redistribute this article (for example to a web site) without written permission from the original author. Failure to do so is a violation of copyright laws.   
  3. You may link to this article from another website, but ONLY if it is not wrapped in a frame. 
  4. You will abide by any additional copyright restrictions which the author may have placed in the article or article's description.
				

— Input and Output

To be useful, a program must input data and output the results of processing that data. This chapter discusses some easy ways to input and output data from the keyboard and monitor. Input and output operations are a very complicated aspect of computers (and computer programming languages), so this chapter is just a beginning.

  • Input and Output Streams.
  • The standard IO streams.
  • Exceptions
  • InputStreamReader and BufferedReader Classes.
  • Converting character data to type int.

Note: If you are reading a Java textbook and are also following these notes you may find that your text book uses its own methods for doing input from the keyboard. This is OK, You can still use these notes. The methods used in these notes are part of the JDK (Java Development Kit) and will work for every Java installation. The methods in your textbook are (probably) unique to that book and require you to use a special package written by the book's author. Those methods are based on the methods in the JDK and are fundamentally the same as the methods used in these notes.

No Built-in IO

Input and output are so common that an abbreviation has been created for them: IO (pronounced eye-oh.) IO operations are very complicated, both at the software level and at the electronic level. Part of the problem is that the way in which data is organized outside the computer is different from the way it is organized inside the computer.

There are no standard statements in the Java language for doing input or output. All input and output is done by using methods that are part of a package. A package is a collection of classes which may be used with other programs. For now, think of a package as a tool box and the classes within it as tools. Several IO packages are available. Usually a programmer picks just one of them, whichever contains the classes needed for the job. These notes use the java.io package, which is the IO package used most often.

It may seem odd to you that Java itself does not have IO built into it. The reason for this is that there are very many types of IO, and a language that has all of them built in would be large and cumbersome. A professional language such as Java (or C or C++ or any of several others) allows the programmer to pick the right IO package for the job.

Note: As mentioned, some text books use their own IO package based on java.io. Those methods will be somewhat different from those described here, but the ideas are the same.

IO Streams

If the car's computer program were written in Java, it would use a specialized IO package that manages sensors and controllers. It would not use the IO package that deals with keyboards and terminals.

In Java, a source of input data is called an input stream and the output data is called an output stream. Think of these streams like this:

In this picture, each "O" is supposed to be a datum (chunk of data) waiting in line to be input, or leaving as output. Inputting data is usually called reading data; and outputting data is usually called writing data (or printing data if the output stream is connected to a monitor or a printer.)

You might think of the input stream as a string of pearls which the program inputs one at a time, in order. The output stream is a string of new pearls (not usually the same ones as came in.) Often a program will have to input several data in a row before it has enough to process. For example, the input data might be a list of numbers, the output data might be their sum.

In general, a program may have several input streams flowing into it and several output streams flowing out of it. For most of the programs in these notes, there are three IO streams:

  • System.in — the input stream.
  • System.out — the output stream for normal results.
  • System.err — the output stream for error messages.

Normally System.in is connected to the keyboard and the data are characters. System.out and System.err both are connected to the monitor, and also are character data. These streams are difficult to manage by themselves. We will use the package java.io to help.

Characters In, Characters Out

The data a keyboard sends to a program is character data, even when the characters include the digits '0' through '9'.

If your program does arithmetic, the input characters will be converted into one of the primitive numeric types. Then the result is calculated (using arithmetic), and then the result is converted to character data. The information a program sends to the monitor is character data:

(Actually, the characters are not really sent directly to the monitor. They, along with everything else the monitor displays, are first converted into a video signal by a graphics card. This business of converting data from one form to another is very common in computers.)

  • Yes, System.out.println("Some string" + 123) sends characters to the ouput stream.
  • Did it have to convert a primitive numeric type to character data?
  • Yes, "Some string" + 123 converts the integer 123 from a primitive numeric type into characters that are appended to "Some string".

Example IO Program

The following program reads characters from the keyboard into the String called inData. Then the characters stored in that String are sent to the monitor. The details of this program are explained in the next several pages.

import java.io.*;
class Echo
{
 public static void main (String[] args) throws IOException
 {
 InputStreamReader inStream = 
new InputStreamReader( System.in ) ;
 BufferedReader stdin = 
new BufferedReader( inStream );
 
 String inData;
 System.out.println("Enter the data:");
 inData = stdin.readLine();
 System.out.println("You entered:" + inData );
 }
}

The line import java.io.*; says that the package java.io will be used. The * means that any class inside the package might be used. Here is how this program runs:

C:\users\default>java Echo
Enter the data:
This is what the user enters
You entered:This is what the user enters

Main Method

Later on we will do something special to convert strings of digits into primitive numeric types. This program does not do that. Here is the program again:

import java.io.*;
class Echo
{
 public static void main (String[] args) throws IOException
 {
 InputStreamReader inStream = 
new InputStreamReader( System.in ) ;
 BufferedReader stdin =
new BufferedReader( inStream );
 
 String inData;
 System.out.println("Enter the data:");
 inData = stdin.readLine();
 System.out.println("You entered:" + inData );
 }
}

The main method of class Echo starts with the line:

 public static void main (String[] args) throws IOException

You have seen most of this line before. This part: throws IOException is necessary for programs that do input (at least for now.) It informs the compiler that main() does an input operation that might fail. When the program is running and an input operation fails, the computer system will be informed of the failure and the program will be gracefully halted.

It would be extremely useful if you played with this program using the copy-paste-and-run method.

Exceptions

On 1950's mainframes and even many 1990's PCs a single input mistake could cause the entire computer system to stop dead (a "crash"). Programs were written with the unreasonable expectation that all input data would be correct and would be read in successfully.

Java is an industrial-strength programming language, and is designed to help the programmer deal with bad data and the all-too-common input failures. When an input or an output operation fails, an exception is generated. An exception is an object (a chunk of main memory) that contains information about what went wrong. The section of code where the problem occurred can deal with the problem itself, or pass the exception on. Passing the exception on is called throwing an exception. The phrase throws IOException in:

public static void main (String[] args) throws IOException

. . .means that the part of the system that started main() must be prepared to deal with an IO exception. For us, all this means is that the program will be halted gracefully.

Java has been proposed as the language for writing airplane traffic control programs. If an IOException occurred in one of those programs, would you expect the system to merely halt gracefully?

BufferedReader

In many real-world programs, the program must keep running no matter what. The program must deal with an exception by fixing the problem or working around it. Java is designed for such programs. Here is the example program again. Look at the first two statements in the main method.

import java.io.*;
class Echo
{
 public static void main (String[] args) throws IOException
 {
 InputStreamReader inStream = 
new InputStreamReader( System.in ) ;
 BufferedReader stdin = 
new BufferedReader( inStream );
 String inData;
 System.out.println("Enter the data:");
 inData = stdin.readLine();
 System.out.println("You entered:" + inData );
 }
}

These statements may look somewhat mysterious. It is a bit too early to explain all their details. For now, just think of them as something messy you do to create a BufferedReader object that does input from the keyboard. The object will be called stdin.

You can think of the two statements as a fill-in-the-blank form. Fill in the blank with the name you want for the BufferedReader:

 InputStreamReader inStream = 
new InputStreamReader( System.in );
 BufferedReader ___________ = 
new BufferedReader( inStream );

Details (if you want them)

Here are some details of what is going on. Skip this page and the next if you want. Look at the two statements:

 InputStreamReader inStream = 
new InputStreamReader( System.in ) ;
 BufferedReader stdin =
new BufferedReader( inStream );

The first statement declares the variable inStream. It has the form you have seen before:

typeName variableName = initialValue ;

Here the typeName is InputStreamReader, a class that is part of the java.io package. You know this is a class, because the type is not one of the eight primitive types. The variable inStream is an object of that data type. onClick="alert('The data type of an object is called its class.')">

In the first statement, the initialValue will be an object. The new operator constructs an object of the requested type. Once the object is constructed (out of main memory) it can be referred to by the variable inStream. (There will be much more on this later in these notes.)

More Details

An InputStreamReader object reads data from some source (such as System.in). However, it is awkward to use by itself. A BufferedReader object is easier to use, but needs to be connected to an InputStreamReader. Look at these two lines from the program:

 InputStreamReader inStream = 
new InputStreamReader( System.in ) ; 
 BufferedReader stdin = 
new BufferedReader( inStream );

The first line constructs an InputStreamReader object and gives it the name inStream. The second line constructs a BufferedReader object and connects it to inStream. The BufferedReader is called stdin. To create a BufferedReader the new operator is used:

BufferedReader stdin = new BufferedReader( inStream );

The new operator creates a BufferedReader object out of main memory. The BufferedReader object can then be used to do input. "BufferedReader" appears twice in this statement because the first "BufferedReader" describes the type of the variable stdin, while the second one tells the new opeator what type of object to create.

Assembly Line

The BufferedReader object uses the InputStreamReader object as its connection to System.in. This connection is made when the BufferedReader is constructed:

BufferedReader stdin = 
 new BufferedReader(inStream );

Think of this as an assembly line: System.in gets characters from the keyboard. The InputStreamReader reads the characters from System.in and hands them to the BufferedReader. The BufferedReader objects hands the data to your program when requested.

Looking at the picture you see why this is called an "input stream". Data streams in from the keyboard through several processing stages before it gets to your program. You don't have to memorize and completely understand all of this right now. It is confusing. In fact, it is here that many text books use their own simpler input methods (which usually does little more than hide what is going on).

One-line Version

Once the connection is made, the variable is not used again. In fact, you don't need to use it at all because the connection can be made all in one line:

BufferedReader stdin = 
 new BufferedReader(new InputStreamReader(System.in));

If you want, you can think of this one very long command that means "get ready to read stuff in." The complete program is now:

import java.io.*;
class Echo
{
 public static void main (String[] args) throws IOException
 {
 BufferedReader stdin = 
new BufferedReader(new InputStreamReader(System.in));
 
 String inData;
 System.out.println("Enter the data:");
 inData = stdin.readLine();
 System.out.println("You entered:" + inData );
 }
}

This one statement takes up two lines. This is OK. Statements end with a semicolon, not at the end of a line. Use indenting to show when a long statement has been written on two (or more) lines.

readLine()

The program reads a line of character data from the keyboard by using the method readLine(), which is part of the BufferedReader object.

inData = stdin.readLine();

It gets a line of characters, and assign them to the String inData. Then the next statement

System.out.println("You entered:" + inData );

writes the string to the monitor. Here is what a run of the program looks like:

Enter the data:
To learn Java, you must play with the programs!
You entered:To learn Java, you must play with the programs!

When you run the program you can correct what you type using the "delete" key and "backspace" key. Only when you hit "enter" are the characters sent to your program.

Numeric Input

Here is another run of the program:

Enter the data:
Columbus sailed in 1492.
You entered:Columbus sailed in 1492.

Notice that the characters '1', '4', '9', and '2' were read in and written out just as were the other characters. Now consider yet another run:

Enter the data:
1492
You entered:1492

Nothing special here. The '1', '4', '9', and '2' are still characters. If you want the user to enter numeric data, your program must convert from character data to a numeric type. The characters are first read into a String object. Then the String object is converted into a numeric type. This is done using a wrapper class.

Integer Input

(It would not be too surprising if you forgot that.) Here is a program that computes the square of a number that the user enters. It uses the one-line method of constructing a BufferedReader.

import java.io.*;
class EchoSquare
{
 public static void main (String[] args) throws IOException
 { 
 BufferedReader stdin = 
new BufferedReader (new InputStreamReader(System.in));
 
 String inData;
 int num, square; // declare two int variables
 System.out.println("Enter an integer:");
 inData = stdin.readLine();
 
 num = Integer.parseInt( inData ); // convert inData to int
 square = num * num ; // compute the square
 System.out.println("The square of " + inData + " is " + square);
 }
}

This program is the previous program with a few additions (in blue). You can copy-paste-and-run it. Better yet, study it for a while, then go to NotePad and see how much you can reconstruct. Now look at this statement:

num = Integer.parseInt( inData ); // convert inData to int

This uses the method parseInt() of the Integer wrapper class. This method takes a String containing an integer in character form. It looks at those characters and calculates an int value. That value is assigned to num.

Converting to Integers

Here is the line from the program, again:

num = Integer.parseInt( inData ); // convert inData to int

Assignment statements work in two steps:

  1. Evaluate the expression on the right of the equal sign,
  2. Put the value in whatever variable is on the left.

In this particular statement, the expression on the right evaluates to an int value by using a method call. Then in the second step that value is assigned to the variable. This process is usually called converting the characters to an integer.

Caution: The string inData is not changed at all. It is "converted" only in the sense that an integer value is calculated based on its contents.

NumberFormatException

If the user enters one of the WRONG lines, the statement inData = stdin.readLine() will work without any problem. It will read in the characters the user typed and put them in the String object inData. However, the method parseInt in the statement num = Integer.parseInt( inData ) will not be able to understand the characters as an integer, and with throw an exception. The user will see something like:

Enter an integer:
14.92
java.lang.NumberFormatException: 14.92

This exception was passed out of the running program to the Java system, which stopped the program and wrote the error message.

The parseInt method is just one method of the wrapper class Integer. It should be used like this:

intVariable = Integer.parseInt( stringVariable );

The stringVariable should contain only characters that can be interpreted as an integer.

Could the following be interpreted as an integer?

" 84"

Notice that there are two spaces preceeding the '8' character.

Another Example

Here is another example, suitable for "copy-paste-and-run." It asks the user for two integers which are to be added together.

import java.io.*;
class AddTwo
{
 public static void main (String[] args) throws IOException
 { 
 BufferedReader stdin = 
new BufferedReader ( new InputStreamReader( System.in ) );
 
 String line1, line2; // declaration of input Strings
 int first, second, sum ; // declaration of int variables
 System.out.println("Enter first integer:");
 line1 = stdin.readLine();
 first = Integer.parseInt( line1 ); // convert line1 to first int
 System.out.println("Enter second integer:");
 line2 = stdin.readLine();
 second = Integer.parseInt( line2 ); // convert line2 to second int
 sum= first + second;// add the two ints, put result in sum
 System.out.println("The sum of " + 
first + " plus " + second +" is " + sum );
 }
}

Study the program for a while. Notice how the indenting and blank lines help in displaying how the program is organized. Here is a sample run of the program:

Enter first integer:
12
Enter second integer:
-8
The sum of 12 plus -8 is 4

Integer Division Tester

Remember that when Java sees + next to a String, it tries to make an even longer string. In this version of the last statement, the Strings line1 and line2 are concatenated to output String. No conversion needs to be done. Then, the int sum is converted to a String, and concatenated to the end.

Here is a new program made by modifying the first program.

  • The user enters two integers, dividend and divisor.
  • The program calculates and prints the quotient and the remainder.
  • The program calculates and prints quotient * divisor + remainder.
import java.io.*;
class IntDivideTest
{
 public static void main (String[] args) throws IOException
 { 
 BufferedReader stdin = 
new BufferedReader ( new InputStreamReader( System.in ) );
 
 String top, bottom; // input Strings
 int dividend, divisor ; // int versions of input
 int quotient, remainder ; // results of "/" and "%"
 System.out.println("Enter the dividend:"); // read the dividend
 top= stdin.readLine();
 dividend = Integer.parseInt( top ); 
 System.out.println("Enter the divisor:"); // read the divisor
 bottom = stdin.readLine();
 divisor = Integer.parseInt( bottom ); 
 quotient = dividend / divisor ;// perform int math
 remainder= dividend % divisor ;
 System.out.println( dividend + " / " + divisor + " is " + quotient );
 System.out.println( dividend + " % " + divisor + " is " + remainder );
 System.out.println( quotient + " * " + divisor + 
" + " + remainder + " is " + (quotient*divisor+remainder) );
 }
}

Run the program a few times. See what happens when negative integers are input.

IF MY ARTICLE IS GOOD AND YOU CAN UNDERSTAND PLEASE VOTE ME .


Other 2 submission(s) by this author

 


Report Bad Submission
Use this form to tell us if this entry should be deleted (i.e contains no code, is a virus, etc.).
This submission should be removed because:

Your Vote

What do you think of this article (in the Beginner category)?
(The article with your highest vote will win this month's coding contest!)
Excellent  Good  Average  Below Average  Poor (See voting log ...)
 

Other User Comments

5/17/2005 8:32:50 PMNeelabh Dutt Upadhyay

Its NICE For Beginners.
(If this comment was disrespectful, please report it.)

 
5/20/2005 7:50:52 AM

I want to know about Bankers Algorithm & Bakery Algorithm in operating system
(If this comment was disrespectful, please report it.)

 
8/2/2005 8:16:44 AMLiese

May you prosper more as you continue to share your intellectual capabilities about programming. Your program was so easily understood because of your clear explanation
(If this comment was disrespectful, please report it.)

 
9/11/2005 4:14:54 PMOcu Kampau

good tutorial...but no javascript there!
(If this comment was disrespectful, please report it.)

 
10/6/2005 8:15:40 AMArun

I am a slow leaner. I felt this too comfortable foe me. Thanks yar!!

(If this comment was disrespectful, please report it.)

 
11/9/2007 9:47:41 AMking sabri

Nice work man
(If this comment was disrespectful, please report it.)

 
1/30/2010 3:41:15 AMdhinakaran

dear sir
I'm final year student in B.sc (geography ) i'm part time work in browsing centra . so how to project work basic and programming code sir pls help me
























(If this comment was disrespectful, please report it.)

 
3/26/2010 4:09:34 PMjacobian

very useful advice.thanks then
(If this comment was disrespectful, please report it.)

 
3/27/2010 3:35:37 AMjacobian

very clear explanation.I like it. :-)
(If this comment was disrespectful, please report it.)

 

Add Your Feedback
Your feedback will be posted below and an email sent to the author. Please remember that the author was kind enough to share this with you, so any criticisms must be stated politely, or they will be deleted. (For feedback not related to this particular article, please click here instead.)
 

To post feedback, first please login.