Exam 2 Review

Arrays

Inheritance/Interfaces

-vocabulary: protected, super, extends, final

-casting

-overriding and partial overriding

Other

-data conversion/casting - primitive types (e.g., double to int, char to int)

-method overloading

-exceptions - checked versus unchecked

Sample Questions:

1. The following code declares and instantiates a HashMap data structure that maps names (Strings) to grade lists (ArrayLists of Doubles). Write one or more lines of code to add a new record to the HashMap as described in the second comment. The record will map the name "Stu Dent" to a list containing three grades [95.0, 88.5, 92.0].

//data structure to map a student's name to a list of that student's grades

HashMap<String, ArrayList<Double>> gradeMap = new HashMap<String, ArrayList<Double>>();

//add a new record to the hashmap that maps from a student

//"Stu Dent" to a list of grades 95.0, 88.5, and 92.0

2. Explain the term partial overriding.

3. Write a method that takes as input an array of integers and an integer target. The method will return true if the target integer is found in the array and false otherwise. You may assume that the array is full. The header of the method is as follows:

public boolean contains(int[] values, int target);

4. What is the output of the following program:

public class Driver {

public static int sum(int[] values) {

int sum = 0;

for(int i = 0; i < values.length; i++) {

sum += values[i];

values[i] = 0;

}

return sum;

}

public static void main(String[] args) {

int[] tester = {1, 2, 3, 4, 5};

System.out.println("Sum: " + sum(tester));

for(int i = 0; i < tester.length; i++) {

System.out.println("[" + i + "]: " + tester[i]);

}

}

}

5. For each of the following code fragments, (1) indicate whether the fragment is valid or invalid and (2) for valid code fragments indicate the output.

(a)

LibraryItem item = new LibraryItem("Vogue");

System.out.println(item);

(b)

Book book = new Book("Steve Jobs", "Walter Isaacson", "1451648537");

System.out.println(book);


(c)

LibraryItem bookitem = new Book("Steve Jobs", "Walter Isaacson", "1451648537");

System.out.println(bookitem);

(d)

Book itembook = new LibraryItem("Vogue");

System.out.println(itembook);

.

public class LibraryItem {


protected String title;


public LibraryItem(String title) {

this.title = title;

}

public String toString() {

return "Title: " + this.title;

}

}

public class Book extends LibraryItem {

private String author;

private String ISBN;


public Book(String title, String author, String ISBN) {

super(title);

this.author = author;

this.ISBN = ISBN;

}


public String toString() {

return super.toString() +

" Author: " + this.author + " ISBN: " + this.ISBN;

}


}