Java Reference
In-Depth Information
4. The call to replace deletes the first two characters (the character at the end position is
not deleted), so ”et” is replaced with a ”d” , resulting in ”drats” .
Therefore, the outcome of the code is
drats
As far as the SCJP exam goes, focus on understanding the insert or append methods of
StringBuilder and StringBuffer because they are the most commonly used methods in
the two classes. Now we change topics and discuss the various classes in Java for perform-
ing input and output.
Input and Output
The java.io package contains a variety of classes that can perform just about any type of
input or output you might need to perform in your Java applications. The trick to master-
ing the java.io package is to understand the difference between stream classes and reader
and writer classes, as well as the difference between low-level and high-level streams. This
section discusses these differences together with the specifi c classes of the java.io package
that you need to know for the SCJP exam.
Let's start with a discussion on streams vs. readers and writers. If you look at the
classes in the java.io package, you will notice a set of classes whose names end in
”InputStream” or “OutputStream” , together with a set of classes that end in “Reader” and
“Writer” . There is a difference between the two:
The stream classes are used for inputting and outputting all types of binary data.
The reader and writer classes are used exclusively for inputting and outputting
character and string data.
For example, the DataInputStream class is a useful input stream that can read all the
primitive types, as well as strings and other binary types. The FileReader class is a reader
that can only read a character or an array of characters from a fi le.
Most of the input classes have a corresponding output class for writing the data. For
example, DataOutputStream writes data that can be read by a DataInputStream , and a
PipedWriter outputs characters to a stream that a PipedReader can read from in a differ-
ent thread.
Now let's discuss the differences between the stream classes and the readers and writers.
Streams vs. Readers and Writers
The stream classes work with raw bytes of data. The parent class of all input streams is the
abstract class InputStream and the parent class of all the output streams is OutputStream .
Figure 4.3 shows the input stream classes in the java.io package, and Figure 4.4 shows the
output streams.
Search WWH ::




Custom Search