Pages

SEM1-FINAL-APCSA-17-18

This exam consists of 15 multiple choice questions and one coding exercise. For each multiple choice question there is at least one correct answer, and there might be more than one correct answer.

Instructions

  1. Write your last name in the upper right hand corner of each page of this exam.
  2. Below your last name, write the name you prefer to be called in class in parentheses.
  3. For each multiple choice question, circle the letter of the correct answer(s).
  4. Follow the instructions for the coding exercise that are provided in that section of the exam.
Each multiple choice question will be graded as follows.
  • Five points will be awarded if and only if all of the correct answers and none of the incorrect answers are circled.
  • Two points will be deducted for each correct answer that is not circled.
  • Three points will be deducted for each incorrect answer that is circled.
  • No more than five points will be deducted per question.

The coding exercise is worth 25 points and comes with the potential for up to 10 bonus points. Partial credit will be awarded. The following grading scale, which is analogous to the scale used for grading programming assignments, will be used when scoring the coding exercise.

MarkPoints
+++31-35
++26-30
+25
✓+24
23
✓-21
-19
--17
00

Don’t Panic!

A Valiant Blessing

May you have Voodoo Donuts to do you good,
Krispy Kreme to sweeten your blood,
Stumptown Coffee to do you no harm
And Einstein Bagels to strengthen your arm.

Q1 = questions[0];

Which of the following character sequences can be used to mark the end of a Java comment?

  1. //
  2. /*
  3. **\
  4. */
  5. *\
  6. </comment>
Correct:11
Incorrect:11

The good news is that although questions about comments have not appeared on previous exams, most students recognized the correct choice. The not-so-great news is that exactly half of those who took the exam did not know that it was the only correct choice.

Too many students chose incorrect answers, including several who did relatively well on the exam in spite of squandering easy points right off the bat. Java comments are certainly not complicated. They are one of the first topics covered in the textbook, and I'm pretty sure they have been emphasized repeatedly in class and in programming assignments. Now is the time to get them squared away in your head if you missed this question.

Choice Times Chosen Comments
a. 7 The characters // mark the beginning of a comment that extends to the end of the line.
b. 0 The characters /* mark the beginning of a comment that may span multiple lines.
c. 4 The characters **\ are not used to delimit comments in Java.
d. 20 Comments that span multiple lines begin with /* and end with */. (Javadoc comments begin with /**.)
e. 3 The characters *\ are not used to delimit comments in Java.
f. 8 The characters </comment> are not used to delimit comments in Java.

Q2 = questions[1];

Which of the following expressions evaluate to true?

  1. true || false
  2. true && false
  3. !true
  4. !false
  5. true && !false
  6. !true || false
Correct:17
Incorrect:5

Most students answered this question correctly. That's good! But if you didn't answer correctly, then ponder this:

  • This question is not difficult.
  • Questions similar — sometimes very similar — to this one first appeared on exam 2 and have appeared on every exam since then.
  • It is imperative that programmers know when simple expressions like these evaluate to true and when they evaluate to false.

More difficult questions than this one are likely to appear on the AP Computer Science A exam. Again, if you missed this question, now is the time to stop and figure out why you missed it and how to avoid missing questions like this again in the future. If you got this question correct, don't let it go to your head. It was really too easy, given the amount of time we've already spent on the topic.

Choice Times Chosen Comments
a. 20 An “or expression” like this one is true if either the value on the left-hand side of the || operator is true (it is true in this case) or the value on the right-hand side is true.
b. 4 An “and expression” like this one is true if and only if the value on the left-hand side of the && operator is true and the value on the right-hand side of the operator is true, which it is not in this case.
c. 0 The expression !true may be read “not true.” And, just like is sounds, the value of the expression is not true.
d. 22 Similiarly !false is “not false.” In other words, the expression is true.
e. 22 (See comment for b.)
f. 0 (See comment for a.)

Q3 = questions[2];

What does the following program print?

public class TF
{
    public static boolean print(boolean p)
    {
        System.out.print(p ? "T" : "F");
        return p;
    }
    public static boolean t() { return print(true); }
    public static boolean f() { return print(false); }
    public static void main(String args[])
    {
        print( (f() && t() && f()) || t() );
    }
}
  1. T
  2. F
  3. FT
  4. FTT
  5. FTF
  6. FTFTT
Correct:1
Incorrect:21

I really like this question. It's certainly more complicated than the previous two, but it's not too difficult for everyone to answer correctly. You only have to understand how simple Boolean expressions work and how to trace the execution of a pretty straight-forward, albeit contrived program. And you have to understand one subtle, important fact about how Java and many other languages behave when evaluating expressions.

Only one student received full credit for his answer to this question. Yang also received the highest total score on the exam, so I'll wager that he earned his 5 points here and didn't just get them by chance. Besides knowing how to work with Boolean expressions and trace the execution of a simple program, this is what Yang apparently understands and everyone else failed to remember: how short-circuit evaluation works.

Anyone who wants to do well on the AP Computer Science A exam (and that should be everyone who takes the exam; otherwise, you're throwing away a lot of good money, to say nothing of wasting valuable time) should be familiar with the contents of this document:

http://media.collegeboard.com/digitalServices/pdf/ap/ap-computer-science-a-course-description.pdf

In particular, students should pay close attention to the sections Topic Outline (pp. 8-10), Commentary on the Topic Outline (pp. 11-12), Java Library Classes and Interfaces (pp. 13-14), The Exam (p. 17 and the example questions on pp. 18-60), and Appendices A, B, and C (pp. 61-76). Those who do will notice that short-circuit evaluation is tucked away on pages 9 and 65 in that nest of topics that you may be tested on.

Unfortunately, you will not find the phrase short-circuit (or short circuit) in the index of the textbook by Sedgewick and Wayne that we are using this year in class. Fortunately, you can read all about short-circuit evaluation on Wikipedia. Moreover, you should have already done so, since I went to the trouble of posting a link to the following Wikipedia article on the study guide for the final exam.

https://en.wikipedia.org/wiki/Short-circuit_evaluation

In case you're reading this and missed the memo: READ ABOUT SHORT-CIRCUIT EVALUATION NOW if you haven't already done so. If you've read about it and still don't understand, then come to me for help. I want to help. I get paid to help. I want to earn my pay. I don't want anyone to lose points when they take the AP exam because they didn't bother to learn about this fairly important, fairly simple topic.

When you think you understand, come back to this question and try to arrive at the correct answer yourself. Try to pretend you've never seen the question before. Also, try to solve the riddle I spent a lot of time composing: What's wrong with Simon? It's not exactly the same thing, but it's very similar.

Finally, it's worth nothing that three students wisely recognized their ignorance and opted to secure three points by not answering the question rather trying to guess at the right answer and risk getting zero points. One student didn't think through the math as well and circled two answers, ensuring a maximum of 2 points and the real possibility of zero.

Moral: Know how the exam you are taking will be scored. Sometimes guessing is the right thing to do. Sometimes it is not. In addition to preparing for exams by studying the content you will be tested on, you also need to prepare for exams by studying the format of the exam and how it is scored. Don't blame me if you fail to guess when guessing can't hurt you. You've been warned!
Choice Times Chosen Comments
a. 10 I'm not very surprised that so many students chose this answer. Disappointed, yes. But not surprised. Students who chose this answer need to look more carefully at what the program does when it executes. Programming is an activity that requires attention to detail.
b. 1 The one student who chose this answer also, not surprisingly, missed the previous question.
c. 1 I suspect the student who chose this answer just guessed wildly, but maybe not. I'm curious.
d. 2 This is the correct answer.
e. 4 I can imagine a couple of ways students might have come to the conclusion that this answer was the correct one. They are wrong, of course, and were probably accompanied by haste or muddled reasoning.
f. 2 This was the best of the wrong answers to choose, because choosing it suggests that you traced the execution of the program correctly and you evaluated the Boolean expression successfully; you simply failed to account for the fact that Java doesn't evaluate any more terms in an expression once it has enough information to determine the value of the expression.

Q4 = questions[3];

What happens when you attempt to compile and execute the following program?

public class Fore
{
    public static void main(String[] args)
    {
        int[] a = {1, 2, 3, 4};
        System.out.print(a[4]);
    }
}

  1. The program produces a run-time error.
  2. The program fails to compile.
  3. The program prints nothing.
  4. The program prints null;
  5. The program prints 4.
  6. None of the above.
Correct:15
Incorrect:7

Two thirds of the class got this question correct. That’s better than half but not good enough. In this question, students are being asked to demonstrate an understanding of two basic facts:

  1. Array indexes (in Java and many other programming languages) begin at index 0, not 1. Hence, a[4] in the question above refers to the 5th element in the array, not the 4th.
  2. When a statement in a program attempts to access an element that is beyond the boundaries of an array — either via an index value that is less than zero or an index value that is greater than or equal to the length of the array — the program will halt when that statement is executed. In other words, the program will halt due to a run-time error, not a compile-time error.
One student did not answer, thereby earning 3 points. Perhaps the student was unsure about whether the program would result in a compile-time or a run-time error; is so, not answering was a mathematically sound move.

Choice Times Chosen Comments
a. 15 This is the correct answer.
b. 3 The program above does, indeed, compile.
c. 0 This wasn't a very attractive answer.
d. 0 Note to self: Neither was this.
e. 2 This was arguably the worst answer to choose. Choosing this answer suggests that you haven't been paying much attention to me or your book.
f. 1 Selecting this answer raises a question: What did you think the program would do? (I'm curious.)

Q5 = questions[4];

Given variables that are declared and initialized as follows, which statements below will cause compile-time errors?

int i = 3;
double d = 1.0;
String s = "0";
boolean b = false;
  1. i = d;
  2. d = i;
  3. i = i / 2;
  4. b = s < 1;
  5. b = b || i < d;
  6. s = i + s;
Correct:1
Incorrect:21

This question tests students' knowledge of important laws of the Java programming language. It's a good example of a question that is really multiple questions rolled into one, all of which deal with the overarching question, Is this legal? Although only one student earned full credit for his answer, several students received partial credit:

  • Number who received 5 points: 1
  • Number who received 3 points: 4
  • Number who received 2 points: 8
  • Number who received 0 points: 9

Choice Times Chosen Comments
a. 10 This statement fails to compile, because Java will not automatically convert a value of type double to a value of type int.
b. 6 This statement will compile, because Java will automatically convert a value of type int to a value of type double.
c. 0 No one was fooled by this choice. It compiles.
d. 18 Attempting to use the greater-than operator to compare a string and a number will cause a compile-time error.
e. 5 This is a perfectly valid statement. The expression on the right-hand side of the assignment operator evaluates to false, and the variable declared on the left-hand side is of type boolean. This is an example of in-line initialization. Perhaps some students thought that you cannot use the greater-than operator to compare a value of type double and a value of type int; you can.
f. 10 When the value on one size of the + operator is a string and the value on the other side is a number, the number is converted to a value of type String and the two String values are concatenated together. So this statement compiles.

Q6 = questions[5];

Which of the following Java expressions evaluates to a value of type int?

  1. 1
  2. 1.0
  3. 4 / 3
  4. 4.0 / 3.0
  5. 4 % 3
  6. 4.0 % 3.0
Correct:20
Incorrect:2

Answers to this question are worth celebrating! Almost everyone was able to identify the correct choices, and everyone received some credit for their answer.

Choice Times Chosen Comments
a. 22 Everyone knows that the literal 1 is treated by Java as being of type int.
b. 22 And everyone knows that 1.0 is not an int. It's a double.
c. 20 A couple people forgot that the division operator (/) returns an int whenever the operands are both of type int. Any fractional amount left over after dividing is discarded.
d. 0 Everyone seems to know that division involving two double values always yields another double.
e. 21 The modulus operator works just like the division operator in terms of the data type of the answer.
f. 0 Ditto.

Q7 = questions[6];

What does the following program print if the value of args is the array of strings {"a", "A", "bb", "a", "bb", "A", "a"}?

public class Tally
{
    public static void main(String[] args)
    {
        int count = 0;
        for (String x : args)
        {
            for (String y : args)
            {
                if (x != y && x.equals(y))
                    count++;
            }
        }
        System.out.print(count / 2);
    }
}

  1. 2
  2. 3
  3. 4
  4. 5
  5. 6
  6. 7
Correct:8
Incorrect:14

This question tests students’ abilities to trace the execution of a short but somewhat sophisticated program involving command-line input, nested loops that use the “enhanced for” (also known as “for-each”) syntax, and integer division. It also requires students to know the difference between String comparison using the != operator, which tests whether the values are the same object, and String comparison using the .equals method, which tests whether the String values are composed of the same sequence of characters, regardless of whether the two values are the same object or not. Three students opted not to answer the question in exchange for a guaranteed 3 points instead of gambling for 5 or 0.

Choice Times Chosen Comments
a. 2
b. 5
c. 3
d. 8 Explain why the program prints 5.
e. 0
f. 0

Q8 = questions[7];

What does the following program print?

public class Geometry
{
    public static void main(String[] args)
    {
        int x = 3, y = 2;
        double[][] plane = { {x, y}, {x / y, x % y} };
        for (double[] line : plane)
        {
            for (double point : line)
            {
                System.out.print(point + " ");
            }
        }
    }
}

  1. 3.0 2.0 1.0 0.0
  2. 3.0 2.0 1.0 1.0
  3. 3.0 2.0 1.5 1.0
  4. 3.0 1.0 2.0 0.0
  5. 3.0 1.0 1.5 1.0
  6. 3.0 1.5 2.0 1.0
Correct:2
Incorrect:20

This question is similar to the previous one. It's the first question of this exam that involves multi-dimensional arrays. To answer correctly, students need to know how the division and modulo operators work, and they need to have a firm handle on how and when values of type int are converted to double. Most students appear to have been tripped up by the data type conversion aspect of the question.

Choice Times Chosen Comments
a. 3
b. 2 This is the correct answer.
c. 17 Why is this answer not correct?
d. 0
e. 0
f. 0

Q9 = questions[8];

What does the following program print, if anything?

public class YetAnotherRecursiveProgram
{
    public static void main(String[] args)
    {
        System.out.print("a");
        if (args != null)
        {
            args = null;
            main(args);
            System.out.print("b");
        }
    }
}

  1. a
  2. ab
  3. aba
  4. aab
  5. The program prints the string ab an indefinite number of times.
  6. The program prints an error message.
Correct:9
Incorrect:13

Choice Times Chosen Comments
a. 3
b. 2
c. 6
d. 9
e. 2
f. 0

Q10 = questions[9];

Which of the statements below would cause a compile-time error if it was appended to the end of the following main method?

public class Matrix
{
    public static void main(String[] args)
    {
        int[][] matrix = new int[2][2];
        int[] array = new int[3];
        matrix[1] = array;
        
        /* append statement here */
    }
}
  1. int a = matrix[0][0];
  2. int b = matrix[0][1];
  3. int c = matrix[1][1];
  4. int d = matrix[1][2];
  5. int e = matrix[2][2];
  6. int f = matrix[2][d];
Correct:11
Incorrect:11

Seven students received partial credit. By virtue of not selecting any answer, two students received 3 points. Five students received received 2 points.

Choice Times Chosen Comments
a. 3
b. 1
c. 0
d. 2
e. 6
f. 19 This is the only correct answer.

Q11 = questions[10];

Which of the statements below would not cause a compile-time error but would trigger an exception (a run-time error) if the statement was inserted at the beginning of the following main method and an attempt was made to compile and execute the program?

public class Foo
{
    public static int bar(int[] a, int n)
    {
        n++;
        return a[1] % n;
    }
    public static void main(String[] args)
    {
        /* insert statement here */

        Foo.bar(values, values[0]);
    }
}
  1. int[] values = { 0 };
  2. int values[] = { 0, 0 };
  3. int[] values = { -1, -1 };
  4. int[] values = { -1, 0 };
  5. int[] values = null;
  6. int[] values = new int[2];
Correct:0
Incorrect:22

Two students received 3 points. Three students received 1 point. Everyone else received 0 points.

Judging by the results, this was a somewhat challenging question. However, it's not that difficult. In fact, the students who received the most points for their choices did not receive the highest overall scores on the exam; they both selected all of the correct answers except for a. (The only students to select choice a., by the way, were among the highest scoring test-takers.)

Choice Times Chosen Comments
a. 2 Correct. Array index out of bounds.
b. 3 Incorrect.
c. 3 Correct. Attempt to divide by zero.
d. 8 Correct. Attempt to divide by zero.
e. 12 Correct. Null object reference.
f. 3 Incorrect. (Array element values are initialized to zero.)

Q12 = questions[11];

Which of the following are valid Java statements?

  1. int x = null;
  2. Integer x = null;
  3. String x = null;
  4. String[] x = null;
  5. char x = null;
  6. Boolean x = null;
Correct:8
Incorrect:14

One student received 3 points; four students received 2 points; and three students received 1 point.

Choice Times Chosen Comments
a. 4 Only variables that hold references to objects can be null.
b. 15
c. 19
d. 20
e. 7 Only variables that hold references to objects can be null.
f. 10

Q13 = questions[12];

Which of the following statements about constructor methods are true?

  1. The name of a constructor method must begin with an uppercase letter.
  2. The name of a constructor method must be the same as the name of the class it belongs to.
  3. The signature of a constructor method does not include a return type.
  4. The return type of a constructor method must be one of the eight primitive types.
  5. A class may have more than one constructor method.
  6. Constructor methods are called when a program uses the keyword new.
Correct:9
Incorrect:13

This question was almost exactly like a question on the previous exam. Six students received 3 points. One student received 2 points.

Choice Times Chosen Comments
a. 2
b. 18
c. 14
d. 4
e. 17
f. 17

Q14 = questions[13];

The authors of Computer Science: An Interdisciplinary Approach formally define the idea of a data type as a set of X and a set of Y, where X and Y are what?

  1. values and operations
  2. ones and zeros
  3. names and values
  4. operations and methods
  5. functions and parameters
  6. none of the above
Correct:19
Incorrect:3

Choice Times Chosen Comments
a. 19 This is a very important concept that is stressed by the authors of your textbook and is central to object-oriented programming. Object-oriented programming is a major topic that will be covered on the AP exam in the second semester of this course.
b. 1
c. 1
d. 0
e. 1
f. 0

Q15 = questions[14];

Which of the following statements about Donald Knuth are true?

  1. Knuth's family didn't have a car until he was in the seventh grade.
  2. Knuth's college calculus teacher would assign, say, the odd number problems in the textbook. Knuth would also do the even numbered problems and the supplementary problems.
  3. Knuth came to believe that his education boiled down to 50% mathematics and 50% writing skills.
  4. Knuth earned his Ph.D. at Caltech.
  5. Knuth was in the unusual position of taking a class his sophomore year at Case for which he had written the textbook the previous summer.
  6. Donald Knuth and his wife Jill have two children, John and Jennifer.
Correct:12
Incorrect:10

Choice Times Chosen Comments
a. 19 True!
b. 20 True!
c. 19 True!
d. 18 True!
e. 18 True!
f. 18 True! This answer was in the handout given to you during the exam, which I strongly encouraged you to read.

Coding Exercise

Read all of the following instructions and notes carefully before you begin working on this portion of the exam.

One page 2 of Chapter 1 of Volume 1 of The Art of Computer Programming, Donald Ervin Knuth writes:

By 1950, the word algorithm was most frequently associated with “Euclid’s algorithm,” a process for finding the greatest common divisor of two numbers which appears in Euclid’s Elements (Book 7, Propositions 1 and 2.) It will be instructive to exhibit Euclid’s algorithm here:

Algorithm E (Euclid’s algorithm).  Given two positive integers m and n, find their greatest common divisor, i.e. the largest positive integer which evenly divides both m and n.

E1. [Find remainder.] Divide m by n and let r be the remainder. (We will have 0 ≤ r < n.)
E2. [Is it zero?] If r = 0, the algorithm terminates; n is the answer.
E3. [Interchange.] Set mn, nr, and go back to step E1. ▮

Write a Java program that implements Euclid’s algorithm. Your program should satisfy the following requirements:

  1. Your program should consist of a single public class called Euclid.
  2. Your class should have a public static method called gcd.
  3. Your gcd method should be defined in terms of two parameters, m and n, of type int.
  4. Your gcd method should return a value of type int.
  5. Your Euclid class should have a main method.
  6. Your main method should be defined in terms of a parameter called args.
  7. Your main method should call your gcd method.
  8. Your main method should convert the first two elements of the parameter variable args (i.e. args[0] and args[1]) from values of type String to values of type int, and it should store those values in final local variables named m and n respectively.
  9. Your main method should use the values of the variables m and n as the first and second arguments respectively when it calls the method gcd.
  10. Your main method should use System.out.println to print the value the method gcd returns.

Bonus Opportunities

  1. Bonus points (up to 5) will be awarded if you meet all of the requirements listed above, and your coding style is impeccable, and you provide an alternate version of the gcd method, and you do so as follows:
    1. The alternate version must be named gcd2.
    2. One version (gcd or gcd2) must be recursive, and the other version must be non-recursive.
    3. Both methods should belong to the Euclid class, and both should be called from your main method.
    4. Your program should verify that gcd and gcd2 return the same value, given the same inputs. If they do not, then something is wrong with one or both of your implementations; in that case, your program should print an error informing the use of that fact.
  2. Bonus points (up to 5) will be awarded if you meet all of the requirements listed above, and your coding style is impeccable, and you implement your gcd method in one line of code, which you can do if you use recursion and Java’s build-in selection operator.



Notes

  1. Your gcd method may assume that the integer arguments passed to the method are greater than zero.
  2. How your main method handles invalid inputs is up to you. It’s fine, for example, for your program to throw an exception message if fewer than two command-line arguments are supplied.
  3. Java's selection operator, P ? a : b, returns one value a if some boolean expression P evaluates to true and another value b if that expression evaluates to false.
  4. Practice writing your program on a piece of scratch paper before attempting to write the final version of your program. When you are satisfied with your preliminary work, plan out and neatly write the final version of your program on a clean sheet of paper. Don't write too closely to any edge of the paper.
  5. Consider writing your program in pencil in case you need to erase mistakes. (Erase thoroughly.)
  6. Correctness, neatness, style, clarity, and simplicity are important.