Name: ______________________________

Choose 5 out of the 7 questions to answer. Cross out the questions you don't want to be graded.

Here are some useful classes, objects, and methods:

.

  1. Define a method that takes an array of Strings as input, and returns the total number of letters in all entries.













  2. Given the following class that represents a cash register, define two methods:

    • getAmount() should return the amount of cash in the register
    • buy(double price, double cash) should handle the transaction of buying an item with the given price using the given cash amount, and return the amount of change required. It should update the amount instance variable to indicate the new amount of cash in the register.

         public class Register {
             private double amount; // Amount of cash in the register
             public Register(double amount) {
                 this.amount = amount;
             }
         }
      













  3. What are the values of a, b, and c at the end of the following program? For each variable, describe the values of any associated instance members.

    public class Point {
        public int x;
        public int y;
    
        public Point(int x, int y) {
            this.x = x;
            this.y = y;
        }
    
        public static void main(String[] args) {
            Point a = new Point(1, 2);
            Point b = new Point(10, 10);
            Point c = a;
            c.x = a.x + b.x;
            c.y = a.y + b.y;
            b.x = b.y;
        }
    }
    













  4. Define the following two static methods:

    • square should take an array of int values as input and return a new array that contains the squares of all the input values. For example, if x = {2, 1, -3}, then square(x) should return {4, 1, 9}.
    • squareInPlace should take an array of int values as input and replace each element of the array with its square. For example, if x = {2, 1, -3}, then after calling squareInPlace(x) the elements of x should be {4, 1, 9}.













  5. What are the values of s(5), s(0), t(2), and t(64), given the following method definitions?

    public static int s(int x) {
        if (x == 0)
            return 0;
        return x + s(x - 1);
    }
    
    public static int t(int x) {
        if (x == 1)
            return 0;
        return 1 + t(x/2);
    }
    













  6. Define a method that takes 2 Strings as input and returns an ArrayList<String> containing all the chars that are in both input values. For example, with inputs "orange" and "brown", the output should be {'r', 'n'}. The order of the output doesn't matter, and it's ok if the same letter appears in the output more than once.













  7. What are the values of a, b, and c at the end of the following program?

    String a =  "";
    int b = 0;
    int c = 5;
    while (c > 0) {
        a += "a";
        if (c < 4) {
            b += c;
        }
    }