Java Reference
In-Depth Information
the array
nameList
, which is an array of references. At this point, no
String
object has been
created. We will create
String
objects and assign them to array elements next.)
Next, consider the statement:
nameList[0] = "Amanda Green";
//Line 2
This statement creates a
String
object with the value
"Amanda Green"
and stores the
address of the object into
nameList[0]
. Similarly, the following statements assign
String
objects, with the given values, to the other elements of
nameList
:
nameList[1] = "Vijay Arora";
//Line 3
nameList[2] = "Sheila Mann";
//Line 4
nameList[3] = "Rohit Sharma";
//Line 5
nameList[4] = "Mandy Johnson";
//Line 6
After the statements in Lines 2 through 6 execute, each element of
nameList
is a
reference to a
String
object, as shown in Figure 9-11.
nameList
nameList[0]
nameList[1]
nameList[2]
nameList[3]
nameList[4]
Amanda Green
Vijay Arora
Sheila Mann
Rohit Sharma
9
Mandy Johnson
FIGURE 9-11
Array
nameList
To output the names, you can use a
for
loop as follows:
for
(
int
index = 0; index < nameList.length; index++)
System.out.println(nameList[index]);
You can use
String
methods to work with the objects of
nameList
. For example, the
expression:
nameList[0].equals("Amanda Green")
evaluates to
true
, while the expression:
nameList[3].equals("Randy Blair")
evaluates to
false
.
Similarly, the expression:
nameList[4].substring(0, 5)
returns a reference to the
String
object with the string
"Mandy"
.
Search WWH ::
Custom Search