Java Reference
In-Depth Information
Because data and list both refer to the same object, when we change data by
saying data[i]++ , we end up changing the object to which list refers. That's why,
after the loop increments each element of data, we end up with the following:
[0]
[1]
[2]
[3]
[4]
list
2
4
6
8
10
data
The key lesson to draw from this discussion is that when we pass an array as a
parameter to a method, that method has the ability to change the contents of the array.
Before we leave the subject of reference semantics, we should describe in more
detail the concept of the special value null . It is a special keyword in Java that is
used to represent “no object”.
null
A Java keyword signifying no object.
The concept of null doesn't have any meaning for value types like int and
double that store actual values. But it can make sense to set a variable that stores a
reference to null . This is a way of telling the computer that you want to have the
variable, but you haven't yet come up with an object to which it should refer. So you
can use null for variables of any object type, such as a String or array:
String s = null;
int[] list = null;
There is a difference between setting a variable to an empty string and setting it
to null . When you set a variable to an empty string, there is an actual object to
which your variable refers (although not a very interesting object). When you set a
variable to null , the variable doesn't yet refer to an actual object. If you try to use
the variable to access the object when it has been set to null , Java will throw a
NullPointerException .
7.4 Advanced Array Techniques
In this section we'll discuss some advanced uses of arrays, such as algorithms that
cannot be solved with straightforward traversals. We'll also see how to create arrays
that store objects instead of primitive values.
Shifting Values in an Array
You'll often want to move a series of values in an array. For example, suppose you
have an array of integers that stores the sequence of values (3, 8, 9, 7, 5) and you
want to send the value at the front of the list to the back and keep the order of the
 
 
Search WWH ::




Custom Search