Java Reference
In-Depth Information
Java provides a convenience class for arrays. The
Arrays
class consists of many static methods to
do handy things such as copy and sort arrays. For example, Listing 3-9 shows one way to sort an array
of ints.
Listing 3-9. Using the Arrays convenience class
int[] a = {5, 4, 3, 2};
// at the top of the program, we had to import
// java.util.Arrays for this to work correctly
Arrays.sort(a);
for (int i = 0; i < a.length; i++) {
System.out.println(a[i]);
}
The result is 2, 3, 4, 5 (each on its own line) in the console.
The Non-Existent Type: null
Java includes a value that isn't anything:
null
. It refers to a memory address that has not been assigned.
In Java terms, that means it refers to an object or primitive that has not been created. As I mentioned in
the “Arrays” section, when you create an array without specifying its values, you are creating a collection
of
null
values. They have no memory address, no corresponding primitive or object exists for them, and
so they are
null
. That might sound like a problem, and the whole concept of
null
often causes novice
programmers some trouble. You can keep it straight by remembering that a
null
is a non-existent
reference.
The oft-maligned
null
has its uses (otherwise, it wouldn't exist—programmers are pragmatic
people, most of the time). For example, we often compare an object to null to be sure that something
exists before we try to use it. If the graphics library is supposed to give us an object of type
Color
and we
get
null
instead, we have a problem. So we might compare that
Color
value to
null
to ensure that we are
getting a
Color
object and do something useful (such as trying another way or at least logging an error)
if not.
Also, it's common practice to create a variable in one place and assign it in another place. In
between the creation and assignment, the value of that variable might be
null
(it also might not be null
because some primitives, such as
int
, have default values). This technique is handy because we might
want to assign different values to the variable based on some logic. For example, a series of
if-else
statements or a
switch
statement might contain code to assign the value of a variable. Let's consider a
small example (from a minesweeper game), shown in Listing 3-10.
Listing 3-10. Using a null value
public getMineIcon(int x, int y) {
// x and y are the position within the game grid
int numberOfAdjacentMines = getNumberOfAdjacentMines(x, y);
MineIcon mineIcon = null; // here's our null