Notes

Arrays store one data type and has a fixed size.

The syntax to create an array is: data type[] name = new data type[num]. This creates an array with constructors.

The other way to create an array is to pre-initialize it. To do this, type data type[] name = {elements}.

The element of arrays can be accessed through the index.

Errors

ArrayIndexOutOfBoundsException: Arrays can be iterated through loops. If the loop accesses an index that the array does not have, this error can occur. An example is listed below:

int[] numbers = {1, 2, 3}; 

for (int i = 0; i <= numbers.length; i++) { // uh-oh
    System.out.println(numbers[i]); 
}
1
2
3
---------------------------------------------------------------------------
java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
	at .(#17:4)

In the example above, the code failed because the for loop iterates from i = 0 to i = 3. The array does not contain an element at index 3. Therefore, the code needs to be altered below:

int[] numbers = {1, 2, 3}; 

for (int i = 0; i < numbers.length; i++) { // uh-oh
    System.out.println(numbers[i]); 
}
1
2
3

for each loop

A for each loop is especially useful to traverse through an array. An example is shown below:

int[] numbers = {1, 2, 3}; 

int sum = 0; 
for (int num : numbers) { // uh-oh
    sum += num; 
}

System.out.println(sum);
6

#3a

public void addMembers(String[] names, int gradYear) {
    for (int i = 0; i < names.length; i++) {
        memberInfo member = new MemberInfo(names[i], gradYear, true);
        memberList.add(member);
    }
    
}

Comments:

My solution matched up with the official solutions. Something that I could have used though, would be the for each loop to iterate through each element in the array.

public void addMembers(String[] names, int gradYear) {
    for (String n : names) {
        memberInfo member = new MemberInfo(n, gradYear, true);
        memberList.add(member);
    }
    
}


Hacks

Hack 1

int[] arrayOne = {1, 3, 5, 7, 9};

for (int i = 0; i < arrayOne.length(); i+=2) {
    System.out.println(arrayOne[i]);
}

Hack 2

B