Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

11. Write a code excerpt that performs the following actions: • Declare an empty

ID: 3700249 • Letter: 1

Question

11. Write a code excerpt that performs the following actions:
• Declare an empty ArrayList named courses that can hold String values.
• Add the courses "ITP 120", "ITE 115", and "ITN 101" to courses.
• Display the number of elements in courses.
• Display whether or not "ITD 256" is an element in courses.
• Remove the element "ITE 115" from courses.

12. Suppose you have an array of 10 elements. What are the legal index values that can be used in the array? What happens if you use an index that is outside this legal range? How can we write code to handle a situation when someone uses an illegal index value?

Explanation / Answer

Question 11

Answer:

ArrayListTester.java

import java.util.ArrayList;

public class ArrayListTester {

public static void main(String[] args) {

ArrayList<String> courses = new ArrayList<String>();

courses.add("ITP 120");

courses.add("ITE 115");

courses.add("ITN 101");

System.out.println("The number of elements in courses: "+courses.size());

System.out.println("ITD 256 exists: "+courses.contains("ITD 256"));

courses.remove("ITE 115");

System.out.println(courses);

}

}

Output:

The number of elements in courses: 3
ITD 256 exists: false
[ITP 120, ITN 101]

Question 12

Answer:

The legal index values for the array with 10 elements are from 0 to 9.

If we use out side of legal indexes in an array then it will throw ArrayIndexOutOfBoundsException.

try {

int value = array[11];

}catch(ArrayIndexOutOfBoundsException e) {

System.out.println("Error occurred");

}