CS 112
Spring 2024

Midterm 1 Practice Problems

Solutions will be posted under Other Content on Blackboard as we get closer to the exam.

These problems are not comprehensive, so make sure to review all of the relevant materials.

  1. What is the output of the following Java code fragment?

    int a = 7;
    int b = a / 2;
    double c = a / 2;
    double d = a / 2.0;
    String e = "b" + a; 
    System.out.println("a = " + a);
    System.out.println("b = " + b);
    System.out.println("c = " + c);
    System.out.println("d = " + d);
    System.out.println("e = " + e);
    
  2. What is the output of the following Java program?

    public class Problem2 {
        public static void method1() {
            System.out.print("X ");
        }
        public static void method2() {
            System.out.print("Y ");
        }
        public static void main(String[] args) {
            for (int i = 0; i < 4; i++) {
                if (i <= 2) {
                    method1();
                } else {
                    method2();
                }
            }
        }
    }
    
  3. What is the output of the following?

    int i, j;                                
    for (i = 0; i <= 4; i += 2) {
        for (j = 1; j < i; j++) {
            System.out.println(i + " " + j);
        }
        System.out.println(i + j);
    }
    
  4. What is the output of the following Java program?

    public class Problem4 {
        public static void main(String[] args) {
            int x = 1;
            int y = 2;
            int z = 3;
            z = mystery(x, z, y);
            System.out.println(x + " " + y + " " + z);
            mystery(y, y, x);
            System.out.println(x + " " + y + " " + z);
        }
    
        public static int mystery(int z, int x, int y) {
            z--;
            x = 2*y + z;
            y = x - 1;
            System.out.println(x + " " + y + " " + z);
            return x;
        }
    }
    
  5. What is the output of the following code fragment?

    int val = 14;
    if (val < 10 && val <= 20) {
        System.out.println("bye");
    } else if (val != 10) {
        System.out.println("eek");
        if (!(val < 10)) {
           System.out.println("ack");
        }
    } else if (val >= 10) {
        System.out.println("bat");
    }
    if (val / 2 == 7) {
        System.out.println("yak");
    }
    
  6. Write a static method named processName that takes as a parameter a string representing a name and does the following:

    • If the name is a one-word name (e.g., “Oprah” or “Bono”), the method should return the number of characters in the name.

    • If the name has more than one word (e.g., “Barack Obama” or “Sarah Jessica Parker”), the method should return the number of spaces in the name.

    For example:

    • processName("Oprah") should return 5
    • processName("Bono") should return 4
    • processName("Barack Obama") should return 1
    • processName("Sarah Jessica Parker") should return 2

    You may assume that multi-word names have one space between each pair of words in the name, and that there are no leading or trailing spaces in the string.

  7. What is the output of the following Java program?

    public class Problem6 {
        public static void main(String[] args) {
            int[] x = {5, 6, 7};
            int y = 4;
            mystery(x, y);
            System.out.println(Arrays.toString(x) + " " + y);
        }
    
        public static void mystery(int[] z, int y) {
            for (int i = 0; i < z.length; i++) {
                z[i] += y;
            }
            y *= 2;
            System.out.println(Arrays.toString(z));
        }
    }
    
  8. Write a static method minGap that takes an array of integers as a parameter and that returns the minimum gap between adjacent values in the array. The gap between two adjacent values in an array is defined as the second value minus the first value. For example, suppose that you have the following array:

    int[] values = {1, 3, 7, 2, 12};
    

    The first gap is 2 (3-1), the second gap is 4 (7-3), the third gap is -5 (2-7), and the fourth gap is 10 (12-2).

    Thus, the call minGap(values) should return -5, because that is the smallest gap in the array. Note that we are not taking the absolute values of the gaps before we compare them, which is why a gap of -5 is smaller than gaps of 2 or 4.

    If the method is passed an array with fewer than 2 elements, it should return 0.

  9. Consider the following lines of Java code:

    int[] a = {5, 4, 3, 2, 1};
    int[] b = {5, 4, 3, 2, 1};
    int[] c = a;
    for (int i = 0; i < b.length; i++) {
        c[i] = b[i];
    }
    b[3] += b.length;
    a[3]--;
    System.out.println(a[3] + " " + b[3] + " " + c[3]);
    
    1. Draw a single memory diagram that shows the final result of these lines. Include both the stack and the heap in your diagram. You may assume that these lines are part of the main method.

    2. Indicate what will be printed by the final line of code shown above.

  10. Write a static method shiftRight that takes an array of integers and shifts all of the array elements one position to the right, with the original last element wrapping around to become the new first element. For example, consider this array:

    int[] values = {0, 2, 4, 6, 8, 10};
    

    After calling shiftRight(values), the contents of the values array should be {10, 0, 2, 4, 6, 8}.

  11. Write a method with the header

    public static int indexLast(int[] arr1, int[] arr2)
    

    that takes two arrays of integers and that returns the index of the last occurrence of the sequence represented by the first array in the second array, or -1 if the sequence represented by the first array does not appear in the second array. For example, suppose that you have these arrays:

    list1: {1, 3, 6}
    list2: {1, 3, 5, 7, 8, 12, 1, 3, 17, 1, 3, 6, 9, 1, 3, 6}
    

    then the call indexLast(list1, list2) should return 13 because the last occurrence of the sequence of values in list1 appears in list2 starting at index 13. You may assume that both arrays have at least one element.

  12. Write a mutator for the Rectangle class from lecture that doubles the width of a Rectangle object.

  13. What is the output of the following Java code fragment?

    Rectangle r1 = new Rectangle(5, 10);
    Rectangle r2 = new Rectangle(5, 10);
    Rectangle r3 = r2;
    System.out.println((r1 == r2) + " " + (r2 == r3));
    
  14. Create a Java class called Triangle. The class should have:

    • two floating-point fields: one for the base of the triangle and one for its height

    • a constructor that takes an initial value for each of the fields

    • accessor and mutator methods for each field

    • a method called area that computes and returns the area of the triangle, which should be a floating-point value that is 0.5 times the product of its base and height.

    • an appropriate toString() method. For example, the code:

      Triangle t = new Triangle(3.0, 4.0);
      System.out.println(t);
      

      should output:

      triangle with base 3.0 and height 4.0
      
    • an appropriate equals() method, that can be used to determine if two Triangle objects have the same base and same height.

    Make sure to employ appropriate encapsulation. Protect the fields from direct access by clients, and make sure that only positive values are assigned to the fields.

  15. Write a client program for your Triangle class. Put it in a class called TriTester, and give it two methods:

    • a static method called processTriangle() that takes a Triangle object as a parameter, prints it, and prints its area. For example, the code:

      Triangle t = new Triangle(3.0, 4.0);
      TriTester.processTriangle(t);
      

      should output:

      triangle with base 3.0 and height 4.0 (area = 6.0)
      

      Take advantage of the methods in the Triangle object.

    • a main() method that does the following:

      • creates three Triangle objects: tri1 (with base 3.0 and height 4.0), tri2 (with base 6.0 and height 6.0), and tri3 (also with base 3.0 and height 4.0)

      • uses processTriangle() to process each of the triangles

      • tests whether tri1 and tri2 are equal and reports the result

      • tests whether tri1 and tri3 are equal and reports the result.

    Here is the desired output of the program:

    tri1: triangle with base 3.0 and height 4.0 (area = 6.0)
    tri2: triangle with base 6.0 and height 6.0 (area = 18.0)
    tri3: triangle with base 3.0 and height 4.0 (area = 6.0)
    tri1 and tri2 are not equal
    tri1 and tri3 are equal
    
  16. Write a subclass of Triangle called EquilateralTriangle. Its constructor should take a single parameter side representing the length of a side. However, the new class should not have any new fields. Rather, it should use the attributes that are inherited from Triangle, and you should initialize those attributes by calling the superclass constructor and passing it the appropriate values. (You should approximate the height of the triangle as 0.866 times the side length.) For example, the following code:

    EquilateralTriangle tri1 = new EquilateralTriangle(6.0);
    System.out.println(tri1);
    

    should initially produce the following output:

    triangle with base 6.0 and height 5.196
    
  17. Override the appropriate method in EquilateralTriangle so that this code:

    EquilateralTriangle tri1 = new EquilateralTriangle(6.0);
    System.out.println(tri1);
    

    will now produce output that looks like this:

    equilateral triangle with side 6.0
    

Questions 17-19 are based on the following Java classes:

public class A extends B {
    public void twist() {
        System.out.println("ho!");
    }
}
public class B {
    public void twist() {
        System.out.println("ouch!");
    }
    public void shout() {
        System.out.println("oh!");
    }
}
public class C extends A {
    public void gasp() {
        System.out.println("why?");
    }
}
  1. You create the following objects of the above classes:

    A a1 = new A();
    B b1 = new B();
    C c1 = new C();
    

    (Note: The above constructor calls are fine, because Java gives us a constructor with no parameters when we don’t define our own constructor.)

    Explain why each of the following method calls either would or would not compile:

    a1.shout()
    a1.gasp()
    b1.twist()
    c1.toString()
    
  2. Given the objects created in the previous problem, what would the output be of the following statements?

    c1.twist();
    c1.shout();
    
  3. Given the above class definitions, which of the following assignment statements would be allowed, and which would not be allowed?

    A a1 = new C();
    A a2 = new B();
    B b1 = new C();
    Object o = new A();
    

    Explain your answers briefly.

  4. Recall the ArrayBag class from lecture. Give this class an accessor method called count() that takes an arbitrary object item and returns the number of times that item occurs in the ArrayBag.

  5. Consider the following method:

    public static int test(int a, int b) {
        if (a < b) {
            return 0;
        } else {
            return 1 + test(a-b, b);
        }
    

    What is returned by the call test(15, 4)?

    How many times is the method called during the execution of test(15, 4) – including the initial call?