AP CSA Unit 1 Assessment
Multiple Choice
1.
The Game class includes the following method.
| Method Signature | Explanation |
|---|---|
public void addPoints(int pts) | Increases the number of points by pts |
Assume that the Game object myGame and the int variable points have been properly declared and initialized in a class other than Game. Which of the following code segments is a valid method call?
A.
myGame.addPoints(int points);
B.
myGame.addPoints(points);
C.
addPoints(Game myGame, int points);
D.
addPoints(myGame, points);
2.
Given the method header double convert(int whole, double fraction), which method call will compile?
A. convert(4.5, 2.0)
B. convert(4, 2.5)
C. convert(4)
D. convert(4, 2.5, 1)
3.
Assume that x is a double variable with a positive value. Which of the following code segments can be used to round x to the nearest integer and store the rounded value in the variable result?
A.
int result = (int) x;
B.
int result = (int) x + 0.5;
C.
int result = (int)(x + 0.5);
D.
int result = (int) x + (int) 0.5;
4.
What is the value of x after the following code executes?
int x = 5;
x += 3;
x *= 2;
A. 10
B. 13
C. 16
D. 18
5.
What is the value of the following expression?
Math.abs(Math.pow(-2, 3)) + Math.sqrt(16)
A. 4.0
B. 8.0
C. 12.0
D. 20.0
6.
Three test scores have equal weight. A final exam is worth twice as much as each test. Which expression correctly calculates the weighted average?
A. (test1 + test2 + test3 + exam) * 2 / 5.0
B. (test1 + test2 + test3 + 2 * exam) / 5.0
C. (test1 + test2 + test3) / 3.0 + 2 * exam
D. (test1 + test2 + test3) / 2.0 + exam / 2.0
7.
The volume of a cylinder is equal to the height times the area of the circular base. The area of the circular base is equal to 𝜋 (pi) times the square of the radius.
The code segment below is intended to compute and print the volume of a cylinder with radius r and height h. Assume that the double variables r, h, and pi have been properly declared and initialized.
/* missing code */
System.out.print(volume);
I.
double baseArea = pi * r * r;
double volume = baseArea * h;
II.
double volume = pi * r * r;
volume = volume * h;
III.
double volume = pi * r * r * h;
Which of the following can be used to replace /* missing code */ so that the code segment works as intended?
A. I only
B. I and III only
C. II and III only
D. I, II, and III
8.
Which of the following code segments can be used to print the output 2526?
A.
int val = 5;
val *= val;
System.out.print(val);
val++;
System.out.print(val);
B.
int val = 5;
val *= val;
System.out.print(val);
val *= 1;
System.out.print(val);
C.
int val = 5;
val += val;
System.out.print(val);
val++;
System.out.print(val);
D.
int val = 5;
val += val;
System.out.print(val);
val *= 1;
System.out.print(val);
9.
The toCelsius method appears in the TemperatureConverter class. The method takes a parameter that represents a temperature in degrees Fahrenheit and correctly returns the equivalent temperature in degrees Celsius. The header for the toCelsius method is shown.
/**
* Returns the Celsius equivalent of a
* Fahrenheit temperature
*/
public static double toCelsius(double fahrenheit)
The following code segment appears in a class other than TemperatureConverter. It is intended to print the Celsius equivalent of 212 degrees Fahrenheit.
double temp = toCelsius(212.0); // Line 1
System.out.println(temp);
Which of the following changes, if any, can be made so that the code segment works as intended?
A. No change is needed; the code segment works as intended.
B. Changing line 1 to double temp.toCelsius(212.0);
C. Changing line 1 to double temp = TemperatureConverter.toCelsius(212.0);
D. Changing line 1 to double temp = toCelsius.TemperatureConverter(212.0);
10.
What is printed when integer addition precedes string concatenation?
System.out.println(4 + 2 + " points");
A. 6 points
B. 42 points
C. 4 + 2 points
D. Compilation error
11.
What is the value of result after the following code executes?
int result = (int) 9.9 * 2;
A. 19
B. 19.8
C. 18
D. Compilation error
12.
Consider the following code segment.
double x = (int) (5.5 - 2.5);
double y = (int) 5.5 - 2.5;
System.out.println(x - y);
What is printed as a result of executing the code segment?
A.
-0.5
B.
0.0
C.
0.5
D.
1.0
13.
What is printed when concatenation starts with a string?
System.out.println("Score: " + 4 + 2);
A. Score: 42
B. Score: 6
C. Score: 4 + 2
D. Score: 4 2
14.
What is printed by a string containing a newline and escaped quotes?
System.out.println("Hi\n\"AP\"");
A. Hi\n"AP"
B. Hi "AP"
C.
Hi
"AP"
D.
Hi
AP
15.
What is printed by consecutive print and println calls?
System.out.print("A");
System.out.print("B");
System.out.println("C");
System.out.print("D");
A. AB C D
B. ABC followed by a newline then D
C. ABCD
D. AB followed by a newline then CD
16.
Consider the following information about the calculateBill method.
- The method is a
staticmethod in theStoreclass. - The method has one
intparameter. - The method has return type
double. - The method can be accessed from another class.
Which of the following code segments, when appearing in a method in a class other than Store, will compile without error?
A.
double tot = calculateBill(5);
B.
double tot = Store.calculateBill(5);
C.
double tot;
tot.calculateBill(5);
D.
double tot = 5.0;
tot.calculateBill();
17.
I. 2 / 5 % 3
II. 2 / (5 % 3)
III. 2 / 5 + 1
Which of the following arithmetic expressions evaluates to 1?
A. I only
B. II only
C. I and II only
D. II and III only
18.
I.
String str = "Good " + "morning," + " sunshine!";
II.
String str = "Good";
str += " morning, sunshine!";
III.
String str = " morning, ";
str = "Good" + str + "sunshine!";
Which of the following code segments can be used to set the value of the string str to "Good morning, sunshine!"?
A. I only
B. II only
C. II and III only
D. I, II, and III
19.
Consider the following code segment.
int first = 5 + 10 * 2;
int second = first + first % 2;
What is the value of second after this code segment is executed?
A. 37
B. 30
C. 26
D. 0
20.
The AnimalPrinter class includes the following two methods.
| Method Signature | Explanation |
|---|---|
public void printDog() | Prints the word "dog" and then moves the cursor to a new line. |
public void printCat() | Prints the word "cat" and then moves the cursor to a new line. |
The method myMethod appears in a class other than AnimalPrinter. The method is intended to produce the following output.
Intended output
dog
cat
Assume that an AnimalPrinter object myPrinter has been properly declared and initialized inside myMethod. Which of the following code segments, if located in myMethod, will produce the intended output?
A.
printDog();
printCat();
B.
printDog(AnimalPrinter);
printCat(AnimalPrinter);
C.
AnimalPrinter.printDog();
AnimalPrinter.printCat();
D.
myPrinter.printDog();
myPrinter.printCat();
21.
Consider the following variable declaration.
int x;
Which of the following values can be stored in the variable x?
A. 0.5
B. 1
C. true
D. false
22.
Which pair of method headers forms a valid overload?
A. int adjust(int x) and double adjust(int x)
B. int adjust(int x) and int adjust(double x)
C. int adjust(int x) and int adjust(int value)
D. int adjust(int x) and int adjust(int x)
23.
Assume that the following variable declarations have been made.
double d = Math.random();
double r;
Which of the following assigns a value to r from the uniform distribution over the range 0.5 ≤ r < 5.5?
A.
r = d + 0.5;
B.
r = d + 0.5 * 5.0;
C.
r = d * 5.0;
D.
r = d * 5.0 + 0.5;
24.
What is the value of x after the following code executes?
double x = (double) 10 / 4;
A. 2
B. 2.0
C. 2.5
D. 4
25.
A program stores a sensor temperature, the number of readings, and whether the sensor is active. Which declarations are most appropriate?
A.
int temperature;
double readings;
String active;
B.
double temperature;
double readings;
boolean active;
C.
double temperature;
int readings;
boolean active;
D.
String temperature;
int readings;
boolean active;
26.
The following is an excerpt of a class specification that appears in an API library.
public class Shirt
The Shirt class is used to create objects that represent shirts.
The Shirt class has color and size variables that hold information about the characteristics of a shirt.
The Shirt constructor initializes a Shirt object with the given color and size.
The getColor and getSize methods return information about a shirt.
A poloShirt object will be declared as type Shirt.
Based on the class specification, which of the following descriptions is accurate?
A. The color and size variables are attributes of the poloShirt object.
B. The color and size variables are behaviors of the poloShirt object.
C. The poloShirt object is an attribute of the getColor and getSize methods.
D. The poloShirt object is a behavior of the getColor and getSize methods.
27.
The Sofa class has only two constructors. Partial declarations of the two constructors are shown.
public Sofa(int numOfSeats, double length, String color) { /* implementation not shown */ }
public Sofa(int numOfSeats, double length) { /* implementation not shown */ }
Which of the following declarations, appearing in a class other than Sofa, will correctly create a Sofa object?
A.
Sofa s1 = new Sofa(3, 7.5);
B.
Sofa s2 = new Sofa(3.0, 8.0);
C.
Sofa s3 = new Sofa("3", "7.5", "brown");
D.
Sofa s4 = new Sofa(3.0, 8.0, "blue");
28.
Consider the following statement.
int r = (int) (Math.random() * 6) + 10;
Which of the following best describes the behavior of the statement?
A. It generates a random integer between 6 and 15, inclusive, and assigns it to r.
B. It generates a random integer between 6 and 16, inclusive, and assigns it to r.
C. It generates a random integer between 10 and 15, inclusive, and assigns it to r.
D. It generates a random integer between 10 and 16, inclusive, and assigns it to r.
29.
A student has created a Song class. The class contains the following three variables.
- A
Stringvariable namedartistto represent the artist name - A
Stringvariable namedtitleto represent the song title - A
Stringvariable namedalbumto represent the album title
The object happyBirthday will be declared as type Song.
Which of the following statements is true?
A. artist, title, and album are instances of the Song class.
B. happyBirthday is an instance of three String objects.
C. happyBirthday is an instance of the Song class.
D. Song is an instance of the happyBirthday object.
30.
Consider the following code segment.
System.out.print("Hello System.out.println");
System.out.print("!!!");
What is printed as a result of executing the code segment?
A.
Hello!!!
B.
Hello System.out.println!!!
C.
Hello
!!!
D.
Hello System.out.println
!!!
31.
Consider the following code segment.
int a = 4;
int b = 5;
a++;
b++;
int c = a + b;
a -= 1;
System.out.println(a + c);
What is printed as a result of executing the code segment?
A.
.
10
B.
.
13
C.
.
14
D.
.
15
32.
Given the method header double average(int total, int count), which statement correctly calls the method and stores its returned value?
A. int result = average(18, 4);
B. double result = average(18.0, 4);
C. double result = average(18, 4);
D. double result = average(18);
33.
Consider the following method.
public double myMethod(int a, boolean b)
{ /* implementation not shown */ }
Which of the following lines of code, if located in a method in the same class as myMethod, will compile without error?
A.
int result = myMethod(2, false);
B.
double result = myMethod(0, false);
C.
double result = myMethod(true, 10);
D.
double result = myMethod(2.5, true);
34.
The Sofa class has only two constructors. Partial declarations of the two constructors are shown.
public class Sofa(int numOfSeats, double length, String color)
{ /* implementation not shown */ }
public class Sofa(int numOfSeats, double length)
{ /* implementation not shown */ }
Which of the following declarations, appearing in a class other than Sofa, will correctly create a Sofa object?
A.
Sofa s1 = new Sofa(3, 7.5);
B.
Sofa s2 = new Sofa(3.0, 8.0);
C.
Sofa s3 = new Sofa("3", "7.5", "brown");
D.
Sofa s4 = new Sofa(3.0, 8.0, "blue");
35.
What is printed when a substring result is not assigned?
String word = "coding";
word.substring(0, 3);
System.out.println(word);
A. cod
B. coding
C. ding
D. Compilation error
36.
The following code segment appears in a method. In the code segment, num1 and num2 are int variables. The method is intended to print the sum of num1 and num2.
int result = num1 + num2;
System.out.println(result);
Which of the following preconditions for the method is most appropriate to avoid an overflow error?
A.
/** Precondition: num1 and num2 are both positive. */
B.
/** Precondition: num1 is not equal to num2 */
C.
/** Preconditions: num1 is between Integer.MIN_VALUE
* and Integer.MAX_VALUE, inclusive.
* num2 is between Integer.MIN_VALUE
* and Integer.MAX_VALUE, inclusive.
*/
D.
/** Precondition: (num1 + num2) is between Integer.MIN_VALUE
* and Integer.MAX_VALUE, inclusive.
*/
37.
Consider the following code segment.
String temp = "comp";
System.out.print(temp.substring(0) + " "
+ temp.substring(1) + " "
+ temp.substring(2) + " "
+ temp.substring(3));
What is printed as a result of executing the code segment?
A. c o m p
B. comp com co c
C. comp omp mp p
D. comp comp comp comp
38.
A teacher has created a Student class. The class contains the following.
- An
intvariable namedgradeto represent the student's grade level - A
Stringvariable namednameto represent the student's name - A
doublevariable namedaverageto represent the student's grade point average - A method named
updateAveragethat updates the value ofaverage
The object greg will be declared as type Student.
Which of the following descriptions is accurate?
A. greg is an instance of the Student class.
B. greg is an instance of three attributes.
C. Student is an instance of the greg object.
D. updateAverage is an instance of the Student class.
39.
Which expression can replace /* missing code */ so the program prints BCEF?
String oldStr = "ABCDEF";
String newStr = /* missing code */;
System.out.println(newStr);
A. oldStr.substring(1, 2) + oldStr.substring(4)
B. oldStr.substring(1, 2) + oldStr.substring(5)
C. oldStr.substring(1, 3) + oldStr.substring(4)
D. oldStr.substring(1, 3) + oldStr.substring(5)
40.
Consider the following description of the MagicNumber class which includes one constructor and two methods.
public MagicNumber() - Constructs a MagicNumber object that represents a number
public void displayNumber() - Displays the number to the screen
public void add_2() - Increases the number by 2
I.
MagicNumber.add_2();
MagicNumber.displayNumber();
II.
MagicNumber n1 = new MagicNumber();
n1.add_2();
n1.displayNumber();
III.
n2.add_2();
n2.displayNumber();
When located in a method in a class other than MagicNumber, which of the following code segments will compile without error?
A. I only
B. II only
C. II and III only
D. None of the code segments will compile.
41.
Which code segment correctly calls the method and stores its returned value?
Assume the following method appears in the same class as the code segment.
public double average(int total, int count) {
return (double) total / count;
}
A. int result = average(18, 4);
B. double result = average(18, 4);
C. double result = average(18.0, 4.0);
D. average = double result(18, 4);
42.
Consider the following class definition.
public class Beverage
{
private int temperature;
public Beverage(int t)
{
temperature = t;
}
public int getTemperature()
{
return temperature;
}
public boolean equals(Object other)
{
if (other == null)
{
return false;
}
Beverage b = (Beverage) other;
return (b.getTemperature() == temperature);
}
}
The following code segment appears in a class other than Beverage. Assume that x and y are properly declared and initialized int variables.
Beverage hotChocolate = new Beverage(x);
Beverage coffee = new Beverage(y);
boolean same = /* missing code */;
Which of the following can be used as a replacement for /* missing code */ so that the boolean variable same is set to true if and only if the hotChocolate and coffee objects have the same temperature values?
A. (hotChocolate == coffee)
B. hotChocolate.equals(coffee)
C. hotChocolate.equals(coffee.getTemperature())
D. hotChocolate.getTemperature().equals(coffee.getTemperature())
43.
Consider the following code segment.
System.out.print("*");
System.out.println("**");
System.out.println("***");
System.out.print("****");
What is printed as a result of executing the code segment?
A.
*
**
***
****
B.
*
**
*******
C.
***
***
****
D.
***
*******
44.
A carpenter would like to know how many 8-inch-long pieces can be cut from a board whose length is measured in feet. Which of the following algorithms can be used to determine the number of pieces?
A.
Step 1: | Divide the length of the board by 8. |
Step 2: | Keep the whole number portion of the result of step 1, and discard the decimal portion. |
Step 3: | Multiply the result of step 2 by 12. |
B.
Step 1: | Divide the length of the board by 12. |
Step 2: | Keep the whole number portion of the result of step 1, and discard the decimal portion. |
Step 3: | Multiply the result of step 2 by 8. |
C.
Step 1: | Multiply the length of the board by 8. |
Step 2: | Divide the result of step 1 by 12. |
Step 3: | Keep the whole number portion of the result of step 2, and discard the decimal portion. |
D.
Step 1: | Multiply the length of the board by 12. |
Step 2: | Divide the result of step 1 by 8. |
Step 3: | Keep the whole number portion of the result of step 2, and discard the decimal portion. |
45.
Consider the following descriptions of two methods that appear in the same class.
| Method Signature | Explanation |
|---|---|
public void methodA(int arg) | Calls methodB with the value of arg * 10 |
public void methodB(int arg) | Displays the value of arg + 10 |
Consider the call methodA(4), which appears in a method in the same class. What, if anything, is printed as a result of the call methodA(4)?
A. 40
B. 50
C. 140
D. Nothing is printed.
Fill & Explain
46.
Initially int a and int b hold arbitrary readings for which a+b and a-b fit in int. The required final values are oldA+oldB and oldA-oldB respectively. Repair the fragment by adding at most one temporary int variable. Explain why simply reordering the two assignments does not work for all inputs.
a = a + b;
b = a - b;
47.
A library documents this class method:
| Signature | Precondition | Postcondition |
|---|---|---|
public static int packsNeeded(int items, int capacity) | items >= 0, capacity > 0 | Returns the smallest number of packs that can hold all items; each pack holds at most capacity items. |
For each call below, state whether its arguments satisfy the precondition. For calls that do, give the guaranteed result. For calls that do not, state whether this specification guarantees an exception.
Supply.packsNeeded(13, 5);
Supply.packsNeeded(0, 5);
Supply.packsNeeded(13, 0);
48.
Assume Book has a public constructor Book(String title). Consider the code below. State how many Book objects are constructed, which variables refer to the same object at the end, and whether missing refers to an empty Book object.
Book first = new Book("A");
Book second = first;
Book third = new Book("A");
Book missing = null;
49.
What is the output of the following code?
int a = 7;
int b = 3;
b = a + b;
a = b - a;
System.out.println(a + " " + b);
Output: ______
50.
What is the output of the following code?
double a = 7;
int b = (int) (a / 2);
double c = (double) b / 2;
System.out.println(b + " " + c);
Output: ______
51.
A parcel record stores code "0042", a whole-number item count 3, a measured mass 2.75, and a paid status of false. Declare four appropriately typed Java variables initialized to those values. Explain why changing code to int and mass to int can each lose required information, and identify whether int mass = 2.75 would compile.
52.
What is the value stored in part?
String word = "banana";
int pos = word.indexOf("na");
String part = word.substring(pos, pos + 3);
Value: ______
53.
Complete the declaration so MAX_SCORE cannot be reassigned.
______ int MAX_SCORE = 100;
54.
The following statements appear inside a method. Identify every line that prevents compilation and explain why. Treat each line independently of errors on other lines.
int remaining; // A
double cost = 4; // B
String label = null; // C
boolean ready = 1; // D
System.out.println(remaining); // E
55.
Complete the expression to print 4.5 without changing the declarations.
int total = 27;
int groups = 6;
double average = ____;
System.out.println(average);
56.
A program initially fails to compile because a semicolon is missing. After that error is fixed, it compiles. It is intended to calculate a decimal average, but one test prints 4.0 when the expected result is 4.5. State what the successful compilation establishes, classify the remaining error, and explain whether testing one additional successful case proves the program correct for all inputs.
57.
Class Pass has exactly these public constructors:
Pass(String name, int visits)
Pass(int visits, double price)
Which calls compile? For each valid call, identify the constructor by its ordered parameter types.
new Pass("Lee", 4); // A
new Pass(4, 12); // B
new Pass(4.0, 12); // C
new Pass(4, "Lee"); // D
58.
Assume min and max are int variables with -1000 <= min < max <= 1000. Write a Java expression that generates a random integer from min to max, inclusive.
Expression: ______
59.
Complete the substring call to remove exactly the first and last characters.
The expression must work for every non-null word of length at least 2.
String word = "PLANET";
String middle = ____;
System.out.println(middle);
60.
Assume all declarations and constructor calls compile. Draw the final variable-to-object reference diagram. Label each constructed object by its creation order rather than by its title. State whether either object has been copied by an assignment.
Book a = new Book("same");
Book b = new Book("same");
Book c = a;
a = b;
b = c;
c = null;
Code Tracing
61.
Write the exact output.
int a = 7;
int b = 3;
String label = "N";
System.out.println(label + a + b);
System.out.println(a + b + label);
System.out.println(label + (a / b) + ":" + (a % b));
62.
Write the exact output.
public int emit(int value) {
System.out.println(value / 2);
return value % 3;
}
// These statements run where emit is directly available.
int first = emit(8);
int second = emit(first + 4);
System.out.println(first + " " + second);
63.
Write the exact output.
double amount = 13;
int whole = (int) (amount / 4);
double half = (double) whole / 2;
System.out.println(whole + " " + half);
64.
Write the exact output. Then identify which comment begins a documentation comment.
/** Displays a label. */
// System.out.println("before");
System.out.print("/* ready */");
/* System.out.println("after"); */
System.out.println("!");
65.
Write the output of string length and space-index arithmetic.
String text = "AP";
text = text + " CSA";
int len = text.length();
int index = text.indexOf(" ");
System.out.println(len - index);
Final output: ______
66.
Write the output after narrowing conversion and integer division.
int num = (int) (9.9 * 2);
double value = num / 4;
System.out.println(value);
Final output: ______
Programming
A complete class or main method is not required unless the task asks for one.
67.
Declare a String record initialized to "blue:harbor". It contains two nonempty fields separated by one colon. Use String methods to print the second field, then a space, then the first field. The example prints "harbor blue". Do not hard-code either field or the position of the colon.
68.
Declare an int totalMinutes initialized to 137. Write Java statements that print the number of whole hours and remaining minutes in the form "2 h 17 min". The calculations must also work if totalMinutes is changed to any nonnegative int. Do not hard-code the quotient or remainder.
69.
Extract and print a suffix using String methods.
You do not need to write the complete main method signature.
Starting with a String containing "programming", write a Java code segment that uses String methods to create and print End: mming. Do not hard-code "mming" or its starting index.
70.
Write Java statements that use exactly one call to Math.random() to assign an equally likely random integer from 2 through 8 inclusive to int ticket, then print ticket. Do not use another random API.
71.
Declare double variables east and north with values 3.0 and 4.0. A robot has moved east units east and north units north. Compute and print the straight-line distance from its starting point using Math.sqrt. Your expression must work for other nonnegative offsets, and the output for these values should be "Distance: 5.0".
72.
Read an integer and a double with Scanner and print their sum.
You do not need to write the complete main method signature.
Write a Java code segment that creates a Scanner, reads an int score followed by a double bonus, and prints their sum as a double. Include any required import, but do not write a complete class.