Activity 9.2.1.
Run the following code. Can you print out the 0th element of the array? Can you print out the (k-j)th element? Which element is that?
arr
, then the elements are named arr[0], arr[1], arr[2], ... arr[n-1]
, where n gives the number of elements in the array. This naming also reflects the fact that the array’s data are contained in storage locations that are next to each other. In Java, as in C, C++, and some other programming languages, the first element of an array has index 0. (This is the same convention we used for String
s.)arr
that contains 15 int
elements. The syntax for referring to elements of an array is arrayname[ subscript ]
arr[j+k]
where j+k
is evaluated to an integer before being used to pull out the array element. Try the code below which uses Figure 9.2.1 as an example. suppose that j and k are integer variables equaling 5 and 7, respectively. Each of the following then would be valid references to elements of the array arr.arr[5.0] // 5.0 is a float and can't be an array subscript
arr["5"] // "5" is a string not an integer
0 ... N-1
, where N
is the number of elements in the array or it is considered out-of-bounds. An out-of-bounds subscript creates a run-time error — that is, an error that occurs when the program is running — rather than a syntax error, which can be detected when the program is compiled. For the array arr
, each of the following expressions contain out-of-bounds subscripts:arr[-1] // Arrays cannot have negative subscripts
arr['5'] // Char '5' promoted to its Unicode value, 53
arr[15] // The last element of arr has subscript 14
arr[j*k] // Since j*k equals 35
IndexOutOfBoundsException
. Try them above to see this exception. (Exceptions are covered in detail in Chapter 10.)0...(N-1)
, where N is the number of elements in the array.new
operator and they have instance variables (for example, length
). Like variables for objects, array variables are considered reference variables. When arrays are used as parameters, a reference to the array is passed rather than a copy of the entire array.Array
class. Thus, arrays don’t fit into Java’s Object
hierarchy. They don’t inherit any properties from Object
and they cannot be subclassed.int,
char, boolean, String, Object, Image, TextField, TwoPlayerGame
and so on.int arr[]; // Declare a name for the array
arr = new int[15]; // Create the array itself
int arr[] = new int[15];
int
and its length
is 15, which is fixed and cannot be changed. This means that the array contains 15 variables of type int
, which will be referred to as arr[0], arr[1],
… arr[14]
.[]
, are used to declare an array type. The brackets can be attached either to the array’s name or to its type, as in the following examples:int arr[]; // The brackets may follow the array's name
int[] arr; // The brackets may follow the array's type
String
s and then uses a for loop to assign the strings "hello1"
, "hello2"
, "hello3"
, "hello4"
, and "hello5"
to the five array locations:String strarr[]; // Declare a name for the array
strarr = new String[5]; // Create the array itself
// Assign strings to the array
for (int k = 0; k < strarr.length; k++) // For each element
strarr[k] = new String("hello" + (k + 1)); // Assign a string
k < strarr.length
specifies the loop bound. Every array has a length
instance variable, which refers to the number of elements contained in the array. As we mentioned, arrays, like String
s, are zero indexed, so the last element of the array is always given by its length-1
. However, length
is an instance variable for arrays, whereas length()
is an instance method for String
s. Therefore, it would be a syntax error in this example to refer to strarr.length()
.length
is an instance variable, not an instance method, as it is for String
s.new
operator to create strarr
, an array of type String
of length five. We then use a String
constructor to create the five String
s that are stored in the array. It is important to realize that creating an array to store five Object
s (as opposed to five primitive data elements) does not also create the Object
s themselves that will be stored in the array.array
of objects is created, the array’s elements are references to those objects (Fig. Figure 9.2.5). Their initial values, like all reference variables, are null
. So to create and initialize the array strarr
, we need to create six objects — the array itself, which will contain five String
s, and then the five String
s that are stored in strarr
.Object
s, an array to store three Student
s plus the three Student
s themselves (Figure 9.2.6):Student school[] = new Student[3]; // A 3 Student array
school[0] = new Student("Socrates"); // The first Student
school[1] = new Student("Plato"); // The second Student
school[2] = new Student("Aristotle");// The third Student
school
to store three Students, and the next three statements create the individual Student
s and assign them to the array (Figure 9.2.6). Thus, creating the array and initializing its elements require four new
statements.Student students[] = new Student[3]; // A 3 Student array
System.out.println(students[0].getName());
students[0]
is a null reference, thus causing the exception.array
does not also create the objects that are stored in the array. They must be instantiated separately. It is a semantic error to refer to an uninstantiated (null
) array element.Student
s to the array, we can refer to them by means of subscripted references. A reference to the Student named “Socrates” is now school[0]
, and a reference to the Student named “Plato” is school[1]
. In other words, to refer to the three individual students we must refer to their locations within school
. Of course, we can also use variables, such as loop counters, to refer to a Student
’s location within school
. The following for loop invokes each Student
’s getState()
method to print out its current state:for (int k = 0; k < school.length; k++)
System.out.println(school[k].getState());
Student
s already existed before the array was created? In that case, we could just assign their references to the array elements, as in the following example (Figure 9.2.8):Student student1 = new Student("Socrates");
Student student2 = new Student("Plato");
Student student3 = new Student("Aristotle");
Student school = new Student[3]; // A 3 Student array
school[0] = student1;
school[1] = student2;
school[2] = student3;
Student
objects can be referenced by two different references — its variable identifier (such as student1
) and its array location (such as school[0]
).arr
that we discussed earlier (Figure 9.2.1), the compiler would allocate storage for 15 int
s —i.e., 60 contiguous bytes of storage, because each int
requires 4 bytes (32 bits) of storage. If we declare an array of 20 double
s,double arr[] = new double[20];
Student
examples and String
examples, because these are objects (not primitive types), the compiler will allocate space for N addresses, where N is the length of the array and where each address requires 4 bytes.int a[] = new int[5];
double b[] = new double[10];
char c[] = new char[30];
String s[] = new String[10];
Student p[] = new Student[5];
false
, and integer and real types are initialized to 0. Reference types—that is, arrays of objects—are initialized to null
.int arr[] = {-2,8,-1,-3,16,20,25,16,16,8,18,19,45,21,-2};
String
s, we can use the following statement:String strings[] = {"hello", "world", "goodbye", "love"};
String
s in the array. Note in these examples that when an array declaration contains an initializer, it is not necessary to use new
and it is not necessary to specify the number of elements in the array. The number of elements is determined from the number of values in the initializer list.arr
and strings
:arr[0] = 5;
arr[5] = 10;
arr[2] = 3;
strings[0] = "who";
strings[1] = "what";
strings[2] = strings[3] = "where";
1, 4, 9 ...
— to the array arr
:for (int k = 0; k < arr.length; k++)
arr[k] = (k+1) * (k+1);
arr
:for (int k = 0; k < arr.length; k++)
System.out.println(arr[k]);
double farr[] = {1.1, 2.2, 3.3, 4.4, 5.5};
farr[1]
?
double farr[] = {1.1, 2.2, 3.3, 4.4, 5.5};
farr[farr.length - 2]
?
farr.length
equals 5.int k = 0;
double farr[] = {1.1, 2.2, 3.3, 4.4, 5.5};
farr
?farr[4]
farr[farr.length-1]
farr[length]
length
.farr[k+4]
int k = 0;
double farr[] = {1.1, 2.2, 3.3, 4.4, 5.5};
farr
?farr(0) = 10.5;
farr[1] = 10.5;
farr[k+1] = 10.5;
farr[k] = 10.5;
farr[0] = 10.5;
farr
from first to last.