AP Computer Science a Quiz: Application Program Interface Api And Libraries
20 questions · exam conditions
0:00
Application Program Interface Api And LibrariesQuestion 1 of 20

A programmer is using a Robot class from a robotics library. The API documentation states that each Robot object keeps track of its current x and y coordinates on a grid and its current direction (e.g., "NORTH"). The class provides methods such as moveForward(), turnLeft(), and getCoordinates().

Based on the documentation, which of the following are considered behaviors of a Robot object?

The actions moveForward(), turnLeft(), and getCoordinates().
The data fields representing the x and y coordinates.
The data field representing the current direction.
The grid on which the robot operates, which is external to the robot object.
← Back to quizzes

AP Computer Science a Quiz

AP Computer Science a Quiz: Application Program Interface Api And Libraries

Practice Application Program Interface Api And Libraries in AP Computer Science a with focused quiz questions that help you check what you know, review explanations, and build confidence with test-style prompts.

What this quiz covers

This quiz focuses on Application Program Interface Api And Libraries, giving you a quick way to practice the rules, question types, and explanations that matter most for AP Computer Science a.

How to use this quiz

Try each quiz question before looking at the correct answer. Use the explanations to review missed ideas, then come back to similar questions until the pattern feels familiar.

All questions

Question 1

A programmer is using a Robot class from a robotics library. The API documentation states that each Robot object keeps track of its current x and y coordinates on a grid and its current direction (e.g., "NORTH"). The class provides methods such as moveForward(), turnLeft(), and getCoordinates().

Based on the documentation, which of the following are considered behaviors of a Robot object?

  1. The actions moveForward(), turnLeft(), and getCoordinates(). (correct answer)
  2. The data fields representing the x and y coordinates.
  3. The data field representing the current direction.
  4. The grid on which the robot operates, which is external to the robot object.

Explanation: The correct answer is A. Behaviors are the actions that an object can perform, which are defined by its methods. The methods moveForward(), turnLeft(), and getCoordinates() represent the robot's behaviors. Choices B and C are attributes (data). Choice D describes the environment, not a behavior of the Robot object itself.

Question 2

A programmer needs to develop a feature that calculates the absolute value of an integer and generates a random decimal number between 0.0 and 1.0. What is the most efficient approach using the standard Java API?

  1. Create a new class named CustomMath with custom methods for absolute value and random number generation.
  2. Search for and download a third-party mathematics library that performs these specific calculations.
  3. Utilize the abs() and random() static methods from the built-in java.lang.Math class. (correct answer)
  4. Write the necessary mathematical logic directly inside the main method where the calculations are needed.

Explanation: The correct answer is C. The standard Java API provides the Math class specifically for common mathematical operations. Using its pre-existing, tested methods is the most efficient and reliable approach. Choices A and D involve unnecessarily reinventing existing functionality. Choice B is also unnecessary because these functions are already part of the standard, built-in library.

Question 3

A developer is using a library for processing files. The library's API documentation describes a class named FileReader. It has methods like open(String path), readLine(), and close(). It also stores the current line number and file path as attributes.

What is the primary role of the FileReader class, based on its documented API?

  1. To store metadata about a file, such as its size and modification date, without reading its content.
  2. To provide a user interface for browsing and selecting files from the computer's file system.
  3. To represent the content of an entire file as a single String in memory.
  4. To define an object that can open a file and read its contents sequentially, line by line. (correct answer)

Explanation: The correct answer is D. The combination of behaviors like open, readLine, and close strongly indicates that the class is designed for sequential file access. It manages the process of reading data from a file rather than just storing metadata (A), providing a GUI (B), or loading the entire file at once (C).

Question 4

A programmer is using a Robot class from a robotics library. The API documentation states that each Robot object keeps track of its current x and y coordinates on a grid and its current direction (e.g., "NORTH"). The class provides methods such as moveForward(), turnLeft(), and getCoordinates().

Based on the documentation, which of the following are considered attributes of a Robot object?

  1. The methods moveForward() and turnLeft() which alter the robot's position.
  2. The getCoordinates() method, which reports the robot's current location.
  3. The x and y coordinates and the current direction of the robot. (correct answer)
  4. The Robot class itself, which serves as the blueprint for all robot objects.

Explanation: The correct answer is C. Attributes refer to the data or state that an object maintains. In this case, the robot's state is defined by its position (x and y coordinates) and its direction. Choices A and B describe behaviors, which are actions implemented as methods. Choice D refers to the class definition, not the attributes of a specific instance.

Question 5

An API for a game development library includes a component responsible for managing a collection of Player objects. This component can add new players, remove players by their username, and provide a count of the total number of players currently in the game.

Based on this description, which of the following programming constructs most likely represents this component?

  1. An attribute, which would store a single piece of data like the player count.
  2. A class, which encapsulates both data (the collection) and behaviors (add, remove, count). (correct answer)
  3. A method, which would perform a single action like adding one player.
  4. A package, which would group this component with other unrelated utility classes.

Explanation: The correct answer is B. The description outlines an entity with both state (the collection of players) and defined behaviors (adding, removing, counting). This combination of data and related operations is the definition of a class. An attribute is only data, a method is only a single behavior, and a package is a grouping of classes.

Question 6

The API documentation for a SoundPlayer class includes the following method signature: public boolean play(String soundFile). The documentation states this method attempts to play a sound file and reports on its success.

What does the boolean keyword in the method signature indicate about the play method?

  1. The method can be called without creating an instance of the SoundPlayer class.
  2. The method requires a logical condition as a parameter in addition to the file name.
  3. The method's implementation details are hidden from the programmer using it.
  4. The method returns a value of either true or false after it completes its execution. (correct answer)

Explanation: The correct answer is D. In a method signature, the type listed before the method name is the return type. boolean indicates that the method will return a Boolean value, which is typically used to signal success (true) or failure (false). Choice A describes a static method. Choice B is a misinterpretation of the return type as a parameter. Choice C describes abstraction, which is a general concept not specific to the boolean keyword.

Question 7

A programmer examines an API and finds a Color class. The documentation shows it has attributes to store integer values for red, green, and blue components. It has behaviors like brighter() and darker() that return new Color objects.

Based on the documented attributes and behaviors, what is the most likely purpose of this Color class?

  1. To represent and manipulate a single color value within a graphics application. (correct answer)
  2. To manage a collection of different colors, such as a palette or a list of favorites.
  3. To draw shapes, such as rectangles and circles, onto a graphical display.
  4. To store the name of a color as a String, such as "red" or "blue".

Explanation: The correct answer is A. The attributes (red, green, blue components) and behaviors (brighter, darker) are all characteristic of an object designed to represent a single, specific color and allow for its modification. The other choices describe different functionalities: a color palette manager (B), a drawing tool (C), or a simple string representation (D).

Question 8

An API for a banking application provides a BankAccount class. The documentation mentions that each BankAccount object has a balance and an accountNumber. It also mentions that the class keeps track of the bank's routing number, which is the same for all accounts created.

In the design of the BankAccount class, which piece of data would most likely be an attribute shared by all instances of the class, rather than unique to each instance?

  1. The current balance of the account.
  2. The unique accountNumber for the account.
  3. The bank's routingNumber. (correct answer)
  4. The name of the individual account holder.

Explanation: The correct answer is C. A routing number is typically the same for all accounts at a particular bank. Therefore, it would be efficiently stored as a single, shared attribute for the entire class (a static variable). The balance, account number, and account holder's name are all unique to each individual BankAccount object and would be instance variables.

Question 9

The Java API documentation for the String class includes the method String substring(int from, int to).

Based on this method signature from the API, what can a programmer conclude about this behavior?

  1. The method modifies the original String object by removing characters.
  2. The method does not return a value but prints the resulting substring to the console.
  3. The method requires two integer parameters and returns a new String object. (correct answer)
  4. The method returns an integer representing the length of the new substring.

Explanation: The correct answer is C. The signature clearly shows two int parameters (from, to) inside the parentheses and a return type of String before the method name. This indicates the method takes two integers and returns a String. Choice A is incorrect as String objects are immutable. Choice B is incorrect because the return type is String, not void. Choice D is incorrect because the return type is String, not int.

Question 10

What is a primary advantage of utilizing pre-existing classes from a well-established library?

  1. The program's overall file size is guaranteed to be smaller than if the functionality were custom-written.
  2. It ensures the program will use less memory, as library code is always more memory-efficient.
  3. It saves development time and leverages reliable, previously tested code for common problems. (correct answer)
  4. It gives the programmer the freedom to modify the library's source code to fix any bugs they find.

Explanation: The correct answer is C. The main benefits of using libraries are code reuse, which saves significant development time, and reliability, as the code has likely been thoroughly tested and used by many others. Choices A and B are not guaranteed; a powerful library might add significant size or memory overhead. Choice D is often not possible, as libraries are frequently distributed without their source code.

Question 11

Which statement best describes the primary purpose of an Application Programming Interface (API) in Java?

  1. It provides a specification of how to interact with a set of classes, detailing their methods and attributes without exposing the implementation. (correct answer)
  2. It is a tool that automatically compiles Java source code into bytecode that can be executed by the Java Virtual Machine.
  3. It is the collection of all Java source code files that make up a program, organized into a single directory or project folder.
  4. It is a security feature that prevents unauthorized access to the methods and variables within a class by encrypting the source code.

Explanation: The correct answer is A. An API serves as a contract or specification that defines how different software components should interact. It exposes the necessary methods and attributes for a programmer to use a class or library without needing to know the underlying implementation details. Choice B describes a compiler. Choice C describes a program's source tree. Choice D incorrectly describes the role of access modifiers like private.

Question 12

Consider the following code that uses the Math class:

double x = -3.7; double y = 2.3; double result1 = Math.abs(x) + Math.ceil(y); double result2 = Math.floor(Math.abs(x)) + Math.round(y);

What are the values of result1 and result2 respectively?

  1. result1 = 6.7, result2 = 5.0 (correct answer)
  2. result1 = 6.7, result2 = 6.0
  3. result1 = 5.7, result2 = 5.0
  4. result1 = 5.7, result2 = 6.0

Explanation: The correct answer is A. Math.abs(-3.7) = 3.7, Math.ceil(2.3) = 3.0, so result1 = 3.7 + 3.0 = 6.7. Math.floor(3.7) = 3.0, Math.round(2.3) = 2, so result2 = 3.0 + 2.0 = 5.0. Choice B incorrectly calculates Math.round(2.3) as 3 instead of 2. Choice C incorrectly calculates Math.ceil(2.3) as 2.0 instead of 3.0. Choice D makes both errors from choices B and C.

Question 13

When using the Random class in Java, which of the following statements about the nextInt() method overloads is correct?

  1. nextInt() returns values from 0 to Integer.MAX_VALUE, while nextInt(n) returns values from 0 to n inclusive
  2. nextInt() returns values from Integer.MIN_VALUE to Integer.MAX_VALUE, while nextInt(n) returns values from 0 to n-1 inclusive (correct answer)
  3. nextInt() returns values from 0 to Integer.MAX_VALUE, while nextInt(n) returns values from 1 to n inclusive
  4. nextInt() returns values from Integer.MIN_VALUE to Integer.MAX_VALUE, while nextInt(n) returns values from 1 to n inclusive

Explanation: The correct answer is B. The parameterless nextInt() method returns any int value including negative values (Integer.MIN_VALUE to Integer.MAX_VALUE), while nextInt(n) returns values from 0 to n-1 inclusive (n is exclusive). Choice A incorrectly states that nextInt() only returns non-negative values and that nextInt(n) includes n. Choice C makes the same error about nextInt() range and incorrectly states nextInt(n) starts from 1. Choice D correctly identifies nextInt() range but incorrectly describes nextInt(n) as starting from 1.

Question 14

A programmer wants to use the ArrayList class to store Integer objects and needs to remove all elements that are greater than 50. Which of the following approaches will correctly accomplish this task without causing runtime errors?

  1. Use a standard for loop iterating forward through the list and call remove() when an element is greater than 50
  2. Use a standard for loop iterating backward through the list and call remove() when an element is greater than 50 (correct answer)
  3. Use an enhanced for loop and call remove() on the ArrayList when an element is greater than 50
  4. Use the Iterator's remove() method within an enhanced for loop when an element is greater than 50

Explanation: The correct answer is B. When removing elements from an ArrayList during iteration, iterating backward prevents index shifting issues that occur when elements are removed. Choice A will cause IndexOutOfBoundsException because removing elements shifts subsequent elements to lower indices. Choice C will throw ConcurrentModificationException because you cannot modify a collection during an enhanced for loop. Choice D is incorrect because enhanced for loops don't provide direct access to the Iterator's remove() method.

Question 15

Consider the following method that processes a list of student names:

public static ArrayList processNames(ArrayList names) { ArrayList result = new ArrayList(); for (String name : names) { if (name.length() > 5) { result.add(name.substring(0, 5).toUpperCase()); } else { result.add(name.toLowerCase()); } } return result; }

If the method is called with the list ["Alice", "Robert", "Jo", "Elizabeth"], what will be the contents of the returned ArrayList?

  1. ["ALICE", "ROBERT", "JO", "ELIZABETH"]
  2. ["Alice", "Robert", "Jo", "Elizabeth"]
  3. ["alice", "ROBER", "jo", "ELIZA"] (correct answer)
  4. ["alice", "robert", "jo", "elizabeth"]

Explanation: This question tests your understanding of string manipulation methods and conditional logic in Java. When tracing through code that processes collections, you need to carefully follow each step and apply the correct methods based on the conditions. Let's trace through the method with the input ["Alice", "Robert", "Jo", "Elizabeth"]: For "Alice" (length = 5): Since 5 is not greater than 5, the condition name.length() > 5 is false, so we execute name.toLowerCase(), giving us "alice". For "Robert" (length = 6): Since 6 > 5, the condition is true, so we execute name.substring(0, 5).toUpperCase(). The substring from index 0 to 5 gives us "Rober", and converting to uppercase yields "ROBER". For "Jo" (length = 2): Since 2 is not greater than 5, we use toLowerCase(), resulting in "jo". For "Elizabeth" (length = 9): Since 9 > 5, we take the first 5 characters with substring(0, 5) to get "Eliza", then convert to uppercase: "ELIZA". The final result is ["alice", "ROBER", "jo", "ELIZA"], which matches answer C. Answer A incorrectly assumes all names get converted to uppercase. Answer B incorrectly assumes no transformations occur. Answer D incorrectly assumes all names get converted to lowercase, ignoring the substring operation for longer names. When tracing through string methods, remember that substring(0, n) extracts exactly n characters starting from index 0, and always check your boundary conditions carefully—"greater than" versus "greater than or equal to" makes a crucial difference.

Question 16

A programmer is working with the following ArrayList operations:

ArrayList list = new ArrayList(); list.add("apple"); list.add("banana"); list.add(1, "cherry"); list.set(0, "apricot"); list.remove("banana");

After all operations are completed, what is the final state of the ArrayList and what value does list.indexOf("cherry") return?

  1. Final list: ["apricot", "banana"], indexOf("cherry") returns -1
  2. Final list: ["apricot", "cherry"], indexOf("cherry") returns 0
  3. Final list: ["cherry", "apricot"], indexOf("cherry") returns 0
  4. Final list: ["apricot", "cherry"], indexOf("cherry") returns 1 (correct answer)

Explanation: When you encounter ArrayList manipulation problems, you need to trace through each operation step-by-step, keeping track of how the list changes after each method call. Let's walk through each operation:

  1. Start with an empty ArrayList
  2. add("apple") → ["apple"]
  3. add("banana") → ["apple", "banana"]
  4. add(1, "cherry") → ["apple", "cherry", "banana"] (inserts "cherry" at index 1, shifting "banana" right)
  5. set(0, "apricot") → ["apricot", "cherry", "banana"] (replaces element at index 0)
  6. remove("banana") → ["apricot", "cherry"] (removes first occurrence of "banana")
The final list is ["apricot", "cherry"], and indexOf("cherry") returns 1 since "cherry" is at index 1. Looking at the wrong answers: Choice A incorrectly shows "banana" still in the list, missing that it was removed. Choice B correctly identifies the final list but claims indexOf("cherry") returns 0, which would mean "cherry" is at the first position. Choice C has the elements in reverse order, suggesting confusion about how add(index, element) works—it doesn't replace elements, it inserts them. Study tip: Practice tracing ArrayList operations by writing down the list state after each method call. Pay special attention to add(index, element) which inserts (shifts elements right) versus set(index, element) which replaces. Also remember that indexOf() returns the first occurrence's index, or -1 if not found.

Question 17

Consider the following code segment that uses the String class methods:

String text = "Programming"; String result1 = text.substring(0, 4); String result2 = text.substring(4); String result3 = result1.toUpperCase(); String result4 = result2.toLowerCase(); String finalResult = result3.concat(result4);

What is the value of finalResult after the code executes?

  1. "PROGramming" (correct answer)
  2. "ProgramMING"
  3. "Proggramming"
  4. "PROGRAMMING"

Explanation: The correct answer is A. text.substring(0, 4) returns "Prog", text.substring(4) returns "ramming". result1.toUpperCase() gives "PROG", result2.toLowerCase() gives "ramming". Concatenating these gives "PROGramming". Choice B incorrectly applies case changes to the wrong substrings. Choice C has an extra 'g' suggesting confusion about substring boundaries. Choice D applies toUpperCase() to the entire string rather than just the first part.

Question 18

public class StringAnalyzer { public static boolean isValidEmail(String email) { return email.contains("@") && email.indexOf("@") == email.lastIndexOf("@") && email.indexOf("@") > 0 && email.indexOf("@") < email.length() - 1; } }

Which of the following email strings would cause the isValidEmail method to return true?

  1. "user@domain@com" - contains multiple @ symbols violating the uniqueness check
  2. "@domain.com" - starts with @ symbol violating the position requirement
  3. "user@" - ends with @ symbol violating the trailing character requirement
  4. "user@domain.com" - contains exactly one @ symbol with characters before and after (correct answer)

Explanation: The correct answer is D. The method checks that: email contains "@", has exactly one "@" (indexOf equals lastIndexOf), "@" is not at the beginning (index > 0), and "@" is not at the end (index < length - 1). Only "user@domain.com" satisfies all conditions. Choice A fails because it has multiple @ symbols. Choice B fails because @ is at position 0. Choice C fails because @ is at the end position.

Question 19

A programmer is building an application that needs to interact with a remote database over a network. What is the most appropriate and common practice for the programmer to take?

  1. Write new, low-level networking code to handle the specific communication protocol of the database.
  2. Utilize a pre-existing library, such as a JDBC driver, that provides classes and methods for database connectivity. (correct answer)
  3. Store all database information in local text files to avoid the complexities of network programming.
  4. Request that the user manually enter database commands into the console for the program to execute.

Explanation: The correct answer is B. Interacting with complex systems like databases is a standard problem for which robust libraries exist. Using a library like a JDBC (Java Database Connectivity) driver provides a reliable, tested API for this task, saving immense time and effort compared to writing the functionality from scratch (A). Choices C and D are not viable solutions for interacting with a remote database.

Question 20

When an API provides a class, such as the ArrayList class, what does this class define for the programmer?

  1. A new set of compiler rules for creating lists of variables.
  2. A new hardware requirement for running the program.
  3. A new primitive data type for storing a dynamic list of items.
  4. A new reference type that can be used to declare variables and create objects. (correct answer)

Explanation: The correct answer is D. In Java, a class is a blueprint for objects and defines a reference type. A programmer can declare a variable of type ArrayList and instantiate an ArrayList object. Choices A and B are incorrect. Choice C is incorrect because ArrayList is a reference type, not a primitive type.