The Nuts and Bolts of the Java Language |
The character-counting program usesto read characters from its input source. TheSystem.in.read()System
class is a member of thejava.lang
package and provides access to system functionality such as standard input and output, copying arrays, getting the current date and time, and properties. Thewhile
loop uses theSystem
class's standard input stream to read characters typed in by the user at the keyboard.In addition, the character-counting program uses the
System
class's standard output stream to display its output:System.out.println(. . .);System.in
is a class variable that is a reference to an object implementing the standard input stream. Similarly,System.out
is a class variable that is a reference to an object implementing the standard output stream. In addition toSystem.in
andSystem.out
, theSystem
class provides a third stream, referred to bySystem.err
, that implements the standard error stream.The standard I/O streams are a C library concept that has been assimilated into the Java language. Simply put, a stream is a flowing sequence of characters; the standard input stream is a stream that reads characters from the keyboard. The standard input stream is a convenient place for an old-fashioned text-based application to get input from the user.
The standard output stream, on the other hand, is a stream that writes its contents to the display. The standard output stream is a convenient place for an old-fashioned text-based application to display its output. And finally, a Java program the standard error stream to display error messages to the user.
Reading from the Standard Input Stream
TheSystem.in.read
method reads a single character and returns either the character that was read or, if there are no more characters to be read, -1. As mentioned before, when a program reads from the standard input stream, the program blocks and waits for you to type something in. The program continues to wait for input until you give it some indication that the input is complete. To indicate to any program that reads from the standard input stream that you have finished entering characters, at the beginning of a new line type the end-of-input character appropriate for your system. When the character-counting program receives an end-of-input character the loop terminates and the program displays the number of characters you typed.Writing to Standard Output
System.out.println
displays itsString
argument followed by a newline.println
has a companion methodSystem
class. TheSystem
class is described completely in Using System Resources. In addition, you can find general information about input and output streams in Input and Output Streams.
The Nuts and Bolts of the Java Language |