Java 101: The ins and outs of standard input/output

Learn the basics of standard input, standard output, and standard error

1 2 Page 2
Page 2 of 2

The PrintStream class provides a println() method, which takes no arguments. That method outputs a single new-line character. Behind the scenes, the various println() methods call their print() method counterparts followed by the no-argument println() method. A close look at the documentation for the no-argument println() method shows the new-line character being obtained from a system property called line.separator. That system property's value is not necessarily the same as \n. (I will discuss system properties in a future article.) To seek true platform independence, don't hard-code \n in your print() or println() arguments. (In this course, the \n literal is often specified in source code.)

Example:

// The following method call is platform-dependent because of the \n character.
System.out.print ("ABC\nDEF");
// The following method calls are platform-independent.
System.out.println ("ABC");
System.out.print ("DEF");

Standard error

The standard error device is that part of the operating system that controls where a program sends error messages. Unlike the standard output device, you cannot redirect standard error on platforms such as Windows 98 SE. Use System.err instead of System.out to distinguish standard error from standard output:

Example:

// Output the following error message to standard error.
System.err.println ("usage: java copy srcfile dstfile");

It's a good idea to use System.err instead of System.out for outputting error messages. After all, a user might become confused if a problem occurs in a program and no error message appears on the screen because the message is sent to the standard output device -- which has been redirected from the screen to a file.

You might wonder why these introductory Java 101 articles don't use GUIs to solicit input and display output. The reason is because Java's GUI framework is more complex than standard I/O, and a complete discussion of this framework reaches far beyond the scope of introductory Java 101 articles. However, several articles from now, you will explore this GUI framework, and your reliance on standard I/O for a program's input and output tasks will diminish.

Word counting

Now that you've explored the concepts of standard input, standard output, and standard error (as well as several simple programs and code fragments that demonstrate these concepts), let's create a useful program that exploits these concepts.

Suppose you want to know how many words an article that you wrote contains. Instead of counting by hand, implement a utility program that counts words for you. Before writing the utility, you need to decide what constitutes a word. After all, it is pointless to write a word-counting program if you don't know how to tell the program how to interpret a word. My definition of a word is a sequence of letters -- either uppercase or lowercase. You could change that definition to include hyphen characters, if desired.

Listing 5 presents the source code to WordCount -- a word-counting program that I've put together. Like myself, you might find this program to be useful.

Listing 5. WordCount.java

// WordCount.java
import java.io.*;
class WordCount
{
   static int nWords;
   public static void main (String [] args) throws IOException
   {
      int ch;
      // Read each character from standard input until a letter
      // is read.  This letter indicates the start of a word.
      while ((ch = System.in.read ()) != -1)
      {
         // If character is a letter then start of word detected.
         if (ch >= 'A' && ch <= 'Z' || ch >= 'a' && ch <= 'z')
         {
             do
             {
                ch = System.in.read ();
                if (ch >= 'A' && ch <= 'Z' ||
                    ch >= 'a' && ch <= 'z' ||
                    ch >= '0' && ch <= '9')
                    continue;
                else
                    break;
             }
             while (true);
             nWords++;
         }
      }
      System.out.println ("\nTotal words = " + nWords);
   }
}

WordCount is pretty straightforward, except for the throws java.io.IOException clause appended to the main() method header. You must include the clause because System.in.read can throw, or pass, an exception -- an object that describes a problem -- to the JVM. (You will explore exceptions in detail in a future article.)

How do you use WordCount? Consider this example: count the number of words in a file called memo.txt by issuing the following command line: java WordCount <memo.txt.

Review

This article sheds the mystery from standard I/O. From a debugging perspective, you will find this simple mechanism to be helpful when developing Java programs -- even programs that present GUIs.

Next month, Java 101 picks up the pace when you begin exploring the object-oriented entities of the Java language.

Jeff Friesen has been involved with computers for the past 20 years. He holds a degree in computer science and has worked with many computer languages. Jeff has also taught introductory Java programming at the college level. In addition to writing for JavaWorld, he has written his own Java book for beginners -- Java 2 By Example, Second Edition (Que Publishing, 2001; ISBN: 0789725932) -- and helped write Special Edition Using Java 2 Platform (Que Publishing, 2001; ISBN: 0789720183). Jeff goes by the nickname Java Jeff (or JavaJeff). To see what he's working on, check out his Website at http://www.javajeff.com.

Learn more about this topic

1 2 Page 2
Page 2 of 2