Classes/Inheritance
Arrays/ArrayLists
2D Arrays
Other
100

Imagine that you have the following class. How would you write a getter for the instance variable bar?

public class Foo {                            
   private double bar                        
                                             
   // Constructors and other methods not shown
}                                            
public double getBar() {
    return bar;        
}                      

Note: 

1) Don't ever use the static keyword! This is almost always wrong, especially for question type 2.

2) All methods should always be public

3) Make sure to include the return type

100

1) What code would you use to create an ArrayList called list to store whole numbers?

2) How would you create an array of size 10 called arr to store whole numbers?

ArrayList:

ArrayList<Integer> list = new ArrayList<Integer>();

Note: Use Integer, not int, for ArrayLists!


Array:

int[] arr = new int[10];

Note: Please make sure you know the difference between how to create a Array and a ArrayList

100
How do you create a 2D array of doubles with 5 rows and 4 columns?

double nums = new double[5][4];

100

Suppose you have two integers x and y. How do you calculate the average (mean) of those two ints?

double average = ((double) (x + y)) / 2;

Note: make sure to cast before dividing! The following code doesn't work:

double average = (double) ((x + y) / 2);

Remember that this is the opposite order when compared to converting from doubles to int, where you want to cast last:

int rand = (int) (Math.random() * 10);

200

You want to create a GroceryList class to keep track of a list of possible items and a total budget. How might you declare the instance variables for this class?

private ArrayList<String> list;

private int budget;


(Note: instance variables are always private)

200

Consider the following method which finds the largest value in a non-empty array:

public static int findMax(int[] arr) {
    int max = /* some value */;      
    for (int x: arr) {                
        max = Math.max(max, x);      
    }                                
    return max;                      
}                                    

Which of the following replacement(s) for /* some value */ will result in the code working properly?

  I. Integer.MIN_VALUE                
 II. 0                                
III. arr[0]                          

I and III only

200

Consider the following method which takes a 2D array as input:

public static void changeMatrix(int[][] mat) {  
    for (int r = 0; r < mat.length; r++) {      
        for (int c = 0; c < mat[0].length; c++) {
            if (r == c) {                        
                mat[r][c] = Math.abs(mat[r][c]);
            }                                    
        }                                        
    }                                            
}                                                

How would you best describe what this method does?

It sets the value of all elements along the diagonal to the absolute value of that element

200

What is the output of mystery(212)?

public static void mystery(int n) {
    System.out.println(n);        
    if (n == 0) {                  
        return;                    
    }                              
    else if (n % 2 == 0) {        
        mystery(n/10);            
    }                              
    else {                        
        mystery(n/2);              
    }                              
}                                  

212

21

10

1

0

300

You want to create two classes to keep track of your progress for studying for the AP Exam. One class, ProblemInfo, will keep track of information for each individual practice problem that you've studied, and another class, APStudy, would consolidate/keep track of all of the ProblemInfo objects. How might you set up the instance variables for these two classes?

ProblemInfo:

private String problemName;

private int selfGrade;

private String notes;


APStudy:

private ArrayList<ProblemInfo> questions;

300

Consider the two following methods which intend to add 1 to every value in an inputted array:

public static void change1(int[] arr) {    
    arr2 = new int[arr.length];            
    for (int i = 0; i < arr2.length; i++) {
        arr2[i] = arr[i] + 1;              
    }                                      
    arr = arr2;                            
}                                          

public static void change2(int[] arr) {    
    for (int i = 0; i < arr.length; i++) {
        arr[i] = arr[i] + 1;              
    }                                      
}                                          

Do both, either, or none of these methods work as intended? Why or why not?                       

Even though change2 is a void method, it works because it is being passed the address to the array.

Change1 does not work because it creates a new array. Setting arr to point to the new array doesn't change any values in the original array.

300

Consider the following method which takes a 2D array as input:

public static void someMethod(int[][] mat) {          
    int height = mat.length;                          
    int numCols = mat[0].length;                      
    for (int col = 0; col < numCols; col++) {          
        for (int row = 0; row < height/2; row++) {    
            mat[height - row - 1][col] = mat[row][col];
        }                                              
    }                                                  
}                                                      

How would you best describe what this method does?

It "mirrors" the top rows to the bottom rows (it copies the values from the top row to the bottom row, second from the top row to the second from the bottom row, etc.)

300

Consider the following code:

int newNum = 0, temp;          
int num = k;                    
while (num > 10) {              
    temp = num % 10;            
    num /= 10;                  
    newNum = newNum * 10 + temp;
}                              
System.out.print(newNum);      

Assuming that num is always positive, which is a true statement about the segment?

I. If 100 <= num <= 1000 initially, the final value of newNum must be in the range 10 <= num <= 100

II. There is no initial value of num that will cause an infinite while loop.

III. If num <= 10 initiailly, newNum will have a final value of 0


II and III only

400

What is the output of the code:

Widget w = new Thingy();

w.methodA();

public class Widget {            
   public void methodA() {        
      System.out.print("1");      
      methodB();                  
   }                              
                                 
   public void methodB() {        
      System.out.print("2");      
   }                              
}                                

public class Thingy extends Widget {
   public void methodA() {        
      super.methodA();            
      System.out.print("3");      
   }                              
                                 
   public void methodB() {        
      super.methodB();            
      System.out.print("4");      
   }                              
}                                

1243

400

Write a method that is given an array of Strings and returns an ArrayList containing all of the Strings from the array in reverse order to how they appeared in the array.

public ArrayList<String> reverse(String[] arr) {          
   ArrayList<String> list = new ArrayList<String>();      
   for (int i = 0; i < arr.length; i++) {                
      list.add(0, arr[i]);                                
   }                                                      
   return list;                                          
}                                                        

OR

public ArrayList<String> reverse(String[] arr) {          
   ArrayList<String> list = new ArrayList<String>();      
   for (int i = arr.length-1; i >= 0; i--) {              
      list.add(arr[i]);                                  
   }                                                      
   return list;                                          
}                                                        
400

Write a method that reverses the elements in each row of a 2D array of integers

public void reverseRows(int[][] mat) {                        
   for (int row = 0; row < mat.length; i++) {                
      for (int col = 0; col < mat[0].length/2; col++) {      
         int temp = mat[row][col];                            
         mat[row][col] = mat[row][mat[0].length-1-row];      
         mat[row][mat[0].length-1-row] = temp;                
      }                                                      
   }                                                          
}                                                            
400

Write a method that is given three Strings as input and returns whether or not exactly 2 of them are equal

public boolean exactlyTwo(String str1, String str2, String str3) {
    if (str1.equals(str2) && str2.equals(str3)) {                
        return false;                                            
    }                                                            
    else {                                                        
        return (str1.equals(str2) ||                              
                str2.equals(str3) ||                              
                str1.equals(str3));                              
    }                                                            
}                                                                

Note: use equals, not ==, to compare Strings!

However, when comparing any primitive data type (e.g. int, double, boolean), use ==!!

500

Suppose we are given this class to represent a street address:

public class Address {              
    private int streetNumber;        
    private String streetName;      
                                     
    public Address(int sNum, sName) {
        streetNumber = sNum;        
        streetName = sName;          
    }                                
}                                    

Write the class for the subclass ApartmentAddress which will be used as follows:

// Creating an Apartment Address to represent                  
// 123 Main St., Apt #205                                      
ApartmentAddress a = new ApartmentAddress(123, "Main St.", 205);
public class ApartmentAddress extends Address {                
   private int apartmentNumber;                                
                                                               
   public ApartmentAddress(int sNum, String sName, int aptNum) {
      super (sNum, sName);                                      
      apartmentNumber = aptNum;                                
   }                                                            
}                                                              

500

Suppose that we are given the following class that represent a train ticket:

public class Ticket {              
    private int rowNumber;        
    private String seatLetter;    
    private double price;          
                                   
    // Constructor not shown      
                                   
    public int getRowNumber() {    
        return rowNumber;          
    }                              
                                   
    public String getSeatLetter() {
        return seatLetter;        
    }                              
                                   
    public double getPrice() {    
        return price;              
    }                              
}                                  

Write a method that is given an ArrayList of tickets as input. The method checks that there are no two seats that are "double-booked". It returns true if no tickets share the same row and seat letter and false otherwise.

public boolean checkNoDoubleBook(ArrayList<Ticket> list) {  
   for (int i = 0; i < list.size(); i++) {                  
      for (int j = i+1; j < list.size(); j++) {              
         Ticket t1 = list.get(i);                            
         Ticket t2 = list.get(j);                            
         if (t1.getRowNumber() == t2.getRowNumber() &&      
             t1.getSeatLetter().equals(t2.getSeatLetter())) {
            return false;                                    
         }                                                  
      }                                                      
   }                                                        
   return true;                                              
}                                                            
500

Write a method that "removes" a given column from a 2D array of integers. After the column is removed, all values should be shifted to the left accordingly, leaving a columns of 0's in the rightmost column.

public void removeColumn(int[][] mat, int colNum) {          
   for (int row = 0; row < mat.length; i++) {                
      for (int col = colNum; col < mat[0].length-1; col++) {
         mat[row][col] = mat[row][col+1];                    
      }                                                      
      mat[row][mat[0].length-1] = 0;                          
   }                                                          
}                                                            
500

Write a method that takes two numbers and returns the largest single digit between the two numbers.

public int largestDigit(int x, int y) {    
   int largestX = 0;                        
   while (x > 0) {                          
      largestX = Math.max(largestX, x % 10);
      x /= 10;                              
   }                                        
                                           
   int largestY = 0;                        
   while (y > 0) {                          
      largestY = Math.max(largestY, y % 10);
      y /= 10;                              
   }                                        
                                           
   return Math.max(largestX, largestY)      
}