Welcome to Lesson 3!


Learning Objectives for Today's Lesson

By the end of today's lesson, you should know...
  • What happens when you try to access an element that is out of the bounds of the array?
  • How do you determine the proper length of an array upon declaration?
  • How do you insert a new element into an array...
    • when order does not matter?
    • when order does matter?
  • How do you remove an element from an array...
    • when order matters?
    • when order does not matter?

1. Array Problems: Determining Array Length Upon Declaration

Arrays: What Happens When You Go Out of Bounds

  • Trying to access an element (slot) that does not exist in the array is a logic error:
    public static void main(String[] args) {
    int array[] = new int[3];
    for (int i = 0; i <= array.length; i++) { //This is an error!
    array[i] = i;
    }
    }
  • Fortunately, the Java compiler throws an ArrayIndexOutOfBounds exception when you try to access an element that is outside of the bounds of the array.
  • Notice that this exception also reports the line number of the problem.
example of an ArrayIndexOutOfBounds error message

Determining Array Length Upon Declaration

  • When declaring an array, the length must be indicated either explicitly or implicitly (static initialization).
  • For example:
String[] names = new String[5]; //length of 5 declared
String[] students = {"Abhijit", "Ly", "Rashad"}; //length of 3 declared
  • It is not possible to declare an array and leave the length blank
String[] names = new String[]; //will not compile
  • The reason that a length must be declared is that the compiler needs to know exactly how much contiguous memory to set aside.
  • However, it is not always possible to know ahead of time how large of an array you will need.
Example class roster for a math class
  • Consider a class roster where students may add or drop, or a list of customer information stored for a particular company, where new customers may constantly be added.
  • If you allocate too little memory, then you may end up with an out of bounds error like the one shown in the example above.
  • In this case, you would be out of luck if you wanted to store a new value inside of the already full array.
  • In contrast, if you allocate too much memory, then some of the memory may end up being unused - a waste of memory.
  • When declaring an array, best practice dictates to indicate a length slightly longer than you anticipate you will need.
  • In other words, you should make your best guesstimate and then leave a little extra space.
  • In such a situation, it will be then be necessary to keep track of the part of the array where values are being stored.
  • For example:
String roster36B[] = new String[50];
int numStudents = 35;
  • Then, each time we add a new student, or a student drops, then we would need to update the value of numStudents.

2. Removing Elements

  • Once we find an element in an array, we may want to remove it from the array
  • Unfortunately, the length of an array cannot change after it is declared.
  • There are two approaches to removing an element from an array - depending on whether the order of the list matters

Approach 1: When Order Does NOT Matter:

  • The order of some lists does not matter.
  • For example, the ordering of elements in your shopping list for the grocery store may be irrelevant.
    • Can you think of other lists you make where order doesn't matter?

  • If the order is not important then:
    1. Overwrite the element to be removed with the last element of the array
    2. Decrement the variable that is tracking the current size of the array by one (typically happens in main)
    3. Note that the provided method does not change the array length variable as the length of an array cannot change after it is declared
  • For instance:
public static void remove(double array[], int indexToErase, int sizeArray) {
    array[indexToErase] = array[sizeArray - 1]; //replace with last element
}

  • The following diagram shows this operation:

Approach 2: When Order DOES Matter:

  • However, in most lists, the order in which you list items does matter.
  • For example, a list of songs to play on an MP3 player:
  • When you ask iTunes to remove a song from the list, you do not expect the last song in the list to appear in place of the song you removed.
  • When order matters then we must:
    1. Write over the element you wish to remove with the next element in the array (at index i+1).
    2. Move all subsequent elements up by one index (each element's index becomes one less).
    3. Shrink the size of the array by returning last element to a default value (Note that the provided function does not change the array length variable as the length of an array cannot change after it is declared)
  • For instance:
public static void remove(double array[], int indexToRemove, int sizeArray) {
    for (int i = indexToRemove; i < sizeArray - 1; i++) {
        array[i] = array[i+1];
    }
    return;
}

  • The following diagram shows this operation:

To remove an element, write over each element with the one after it, starting at the index to remove



Video: Removing an Element from an Array





Activity 3.1: Removing an Element from An Array (10 pts)

  • Copy and paste the below starter code into a file called ArrayAddDrop.java
  • Complete the lines of code where noted in bold.
  • When your program is working as shown in the sample output, submit ArrayAddDrop.java to Canvas.
/**
* @author
* CIS 36B
*/
import java.util.Scanner;

public class ArrayAddDrop {
    
    public static void main(String[] args) {
      
        Scanner input = new Scanner(System.in);
        int indexToDrop;
        int numStudents = 5; //current number on roster
        String roster[] = new String[10]; //guesstimate of length will need
        
       
roster[0] = "Ali";
       
roster[1] = "Bao";
       
roster[2] = "Chloe";
       
roster[3] = "Danika";
       
roster[4] = "Eduardo";
       

        System.out.println("Current Roster:");
        printArray(roster, numStudents);
        System.out.print("\nEnter the number of the student to drop: ");
        indexToDrop = input.nextInt();
        remove(roster, numStudents, indexToDrop);
        //decrement numStudents variable
        System.out.println("\nCurrent Roster:");
        printArray(roster, numStudents);
       
        System.out.println("Total enrolled in the class: "
            + numStudents + " students");
       
    }
    
    /**
     * Removes an element from an array at a specified index
     * @param array the list of String values
     * @param numElements the current number of elements stored
     * @param indexToRemove where in the array to remove the element
     */
    
    public static void remove(String array[], int numElements, int indexToRemove) {
        for (int i = indexToRemove; i < numElements - 1; i++) {
            array[i] = //you fill in here!
        }
        return;
    }

    /**
     * Print an array of Strings to the console
     * @param array the list of String values
     * @param numElements the current number of elements stored
     */
    public static void printArray(String[] array, int numElements) {
        for (int i = 0; i < numElements; i++) {
            System.out.println(i + ". " + array[i]);
        }
    }

}

Sample Output:

Current Roster:
0. Ali
1. Bao
2. Chloe
3. Danika
4. Eduardo

Enter the number of the student to drop: 2

Current Roster:
0. Ali
1. Bao
2. Danika
3. Eduardo

Total enrolled in the class: 4 students



3. Inserting Elements into an Array

  • Just like when removing an element from an array, when we insert, there are two possible options:

Inserting an Element When Order Does NOT Matter:

  • If we want to add an item to an array, the easiest way is to place it at the end of the array.
int array[] = new int[10];
array[0] = 10;
array[1] = 15;
array[2] = 20;
//keep track of current number of elements in the array
int currNumElements = 3;

//now insert new value
int newValue = 12;
array[3] = newValue;
currNumElements++; //increase counter
  • The above example assumes you have allowed adequate space to insert new elements.
  • However, the current number of elements in the array must be less than its length, or there will be no space to insert a new element into the array.
//allot space only for initial elements to be inserted
int array[] = new int[3];
array[0] = 10;
array[1] = 15;
array[2] = 20;
//now try to insert new value
int newValue = 12;
array[3] = newValue; //produces an error
   

The above produces the following the error message at runtime:

Inserting an Element When Order DOES Matter:

  • However, if we are trying to maintain an ordered list of elements, then we will not always be able to insert at the end of the array.
  • What if we want to insert an item in the middle of a array?
  • In this case, we must:
  • Move all elements after the insertion location down by one slot (the index of these elements increases by one)
  • Assign the new value to the element at the insertion slot
  • The following diagram shows this operation

Video: Inserting an Element into an Array



Activity 3.2: Inserting an Element into an Array (10 pts)

  • Open up ArrayAddDrop.java from the last activity. We are going to add onto this program.
  • First we are going to offer the user the option to either add or drop a student.
  • Declare two new variables at the top of main    
int indexToAdd;
String choice;
  • Next, add the following lines of code to your program beneath the first call to printArray in main:         
               System.out.print("\nWould you like to add or drop a student?"
                + "\nType 'ADD' or 'DROP': ");
        choice = input.next();
       
        if(choice.equalsIgnoreCase("DROP")) {
            //add the code here to drop a student
       
        } else if (choice.equalsIgnoreCase("ADD")) {
            input.nextLine(); //clear '\n' from input
            System.out.print("\nEnter the name of the student to add: ");
            String newName = input.nextLine();
            System.out.print("\nEnter the position on the roster: ");
            indexToAdd = input.nextInt();
            //Call insert method here
            //increment numStudents variable
       
        } else {
            System.out.println("\nInvalid input. Please re-run program "
                    + "to try again.");
        }

        //code for print out of current roster should go here

  • The contents of your main method should now look identical to the following:
ArrayAddDrop.java current version

  • Next, cut and paste the code for dropping a student (except the part where you print the updated roster) and place it inside the if statement's curly braces.
  • Your if statement should now look like this:
if(choice.equalsIgnoreCase("DROP")) {
    System.out.print("\nEnter the number of the student to drop: ");
    indexToDrop = input.nextInt();
    remove(roster, numStudents, indexToDrop);
    numStudents--;
    }
  • Then, copy and paste the below method and add it to your program:
    /**
     * Inserts an element into an array at a specified index
     * @param array the list of String values
     * @param numElements the current number of elements stored
     * @indexToInsert the location in the array to insert the new element
     * @param newValue the new String value to insert in the array
     */
  
    public static boolean insert(String array[], int numElements,
            int indexToInsert, String newValue) {
        if (array.length == numElements) {
            System.out.println("Array is full. No room to insert.");
            return false;
        }
      
        //start at end and work backwards shifting names down
        for (int i = numElements; i > indexToInsert; i--) {
            array[i] = //you fill in here
        }
        array[indexToInsert] = newValue;
        return true;     
    }
  • It is your job to finish writing the insert method by filling in the missing line.
  • You will also need to add the two missing lines to the else if statement in main
    • Hint: Create a boolean variable and assign the result of the method call to this variable
    • Only if the method returns true, should you increment the numStudents variable - do you understand why?
  • Note that the insert method should insert into an array whose length is larger than its current size.
    • Therefore, the method begins by performing some error checking.
  • Next, the method needs to shift down all of the items in the array starting from the index of the new value that you wish to insert all the way down to the last element in the array.
    • In other words, the method needs to create a hole inside the array to insert into
    • It does so by shifting elements down to create space to insert a new element at the desired index.
  • When you are finished writing your method, run your program and make sure the new element was inserted into the correct location.
  • Once everything is running properly as shown in the sample output, upload your AddDropArray.java file to Canvas.

Sample Output:

Current Roster:
0. Ali
1. Bao
2. Chloe
3. Danika
4. Eduardo

Would you like to add or drop a student?
Type 'ADD' or 'DROP': ADD

Enter the name of the student to add: Chris

Enter the position on the roster: 3

Current Roster:
0. Ali
1. Bao
2. Chloe
3. Chris
4. Danika
5. Eduardo

Total enrolled in the class: 6 students

Wrap Up

  • Answer the practice exam questions for this lesson on Canvas.

Upcoming Assignments

  • Lesson 3 Practice Exam Questions: Due Tuesday at 11:59pm on Canvas
  • Activities 3.1 and 3.2: Due Tuesday at 11:59pm on Canvas
  • Lab 2: Due Monday at 11:59pm on Canvas.
  • Quiz 2: Due Friday at midnight on Canvas

~ Have a Great Day! ~