img
Writing Console Output
Console output is most easily accomplished with print( ) and println( ), described earlier,
which are used in most of the examples in this topic. These methods are defined by the
class PrintStream (which is the type of object referenced by System.out). Even though
System.out is a byte stream, using it for simple program output is still acceptable. However,
a character-based alternative is described in the next section.
Because PrintStream is an output stream derived from OutputStream, it also implements
the low-level method write( ). Thus, write( ) can be used to write to the console. The simplest
form of write( ) defined by PrintStream is shown here:
void write(int byteval)
This method writes to the stream the byte specified by byteval. Although byteval is declared
as an integer, only the low-order eight bits are written. Here is a short example that uses
write( ) to output the character "A" followed by a newline to the screen:
// Demonstrate System.out.write().
class WriteDemo {
public static void main(String args[]) {
int b;
b = 'A';
System.out.write(b);
System.out.write('\n');
}
}
You will not often use write( ) to perform console output (although doing so might be
useful in some situations), because print( ) and println( ) are substantially easier to use.
The PrintWriter Class
Although using System.out to write to the console is acceptable, its use is recommended
mostly for debugging purposes or for sample programs, such as those found in this topic.
For real-world programs, the recommended method of writing to the console when using
Java is through a PrintWriter stream. PrintWriter is one of the character-based classes.
Using a character-based class for console output makes it easier to internationalize your
program.
PrintWriter defines several constructors. The one we will use is shown here:
PrintWriter(OutputStream outputStream, boolean flushOnNewline)
Here, outputStream is an object of type OutputStream, and flushOnNewline controls whether
Java flushes the output stream every time a println( ) method is called. If flushOnNewline is
true, flushing automatically takes place. If false, flushing is not automatic.
PrintWriter supports the print( ) and println( ) methods for all types including Object.
Thus, you can use these methods in the same way as they have been used with System.out.
If an argument is not a simple type, the PrintWriter methods call the object's toString( )
method and then print the result.
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home