Java Reference
In-Depth Information
whether there are no exceptions, handled exceptions, or unhandled excep-
tions. The code to handle the
close
is complex because
1.
fileIn
must be declared outside of the
try
block in order to be
visible in the
finally
block.
2.
fileIn
must be initialized to
null
to avoid compiler complaints
about a possible uninitialized variable.
3.
Prior to calling
close
, we must check that
fileIn
is not
null
to
avoid generating a
NullPointerException
(
fileIn
would be
null
if the file was not found, resulting in an
IOException
prior to its
assignment).
4.
In some instances, but not in our example,
close
might itself
throw a checked exception, and would then require an additional
try/catch
block.
Formatted file output is similar to file input.
FileWriter
,
PrintWriter
, and
println
replace
FileReader
,
Scanner
, and
nextLine
, respectively. Figure 2.20
illustrates a program that double-spaces files that are specified on the com-
mand line (the resulting files are placed in a file with a
.ds
extension).
This description of Java I/O, while enough to do basic formatted I/O,
hides an interesting object-oriented design that is discussed in more detail in
Section 4.5.3.
FileWriter
is used
for file output.
This chapter examined reference types. A
reference
is a variable that stores
either the memory address where an object resides or the special reference
null
. Only objects may be referenced; any object can be referenced by several
reference variables. When two references are compared via
==
, the result is
true
if both references refer to the same object. Similarly,
=
makes a reference
variable reference another object. Only a few other operations are available.
The most significant is the dot operator, which allows the selection of an
object's method or access of its internal data.
Because there are only eight primitive types, virtually everything of con-
sequence in Java is an object and is accessed by a reference. This includes
String
s, arrays, exception objects, data and file streams, and a string tokenizer.
The
String
is a special reference type because
+
and
+=
can be used for con-
catenation. Otherwise, a
String
is like any other reference;
equals
is required to
test if the contents of two
String
s are identical. An
array
is a collection of iden-
tically typed values. The array is indexed starting at 0, and index range checking
is guaranteed to be performed. Arrays can be expanded dynamically by using
Search WWH ::
Custom Search