AP Computer Science a Quiz: Methods How To Write Them
19 questions · exam conditions
0:00
Methods How To Write ThemQuestion 1 of 19

Which statement about method scope is correct for this code? ```java public class Demo { public static int factorial(int n){ int prod = 1; for(int i=2;i<=n;i++){ int step = i; // loop-only prod *= step; } return prod; } }

step is accessible anywhere in factorial after the loop ends.
prod is accessible only inside the for-loop body.
i is accessible after the for-loop because it is an int.
step is accessible only inside the for-loop block where declared.
← Back to quizzes

AP Computer Science a Quiz

AP Computer Science a Quiz: Methods How To Write Them

Practice Methods How To Write Them 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 Methods How To Write Them, 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

Which statement about method scope is correct for this code? ```java public class Demo { public static int factorial(int n){ int prod = 1; for(int i=2;i<=n;i++){ int step = i; // loop-only prod *= step; } return prod; } }

  1. step is accessible anywhere in factorial after the loop ends.
  2. prod is accessible only inside the for-loop body.
  3. i is accessible after the for-loop because it is an int.
  4. step is accessible only inside the for-loop block where declared. (correct answer)

Explanation: This question tests AP Computer Science A skills, specifically the understanding of variable scope within methods and block structures. In Java, variables declared inside a block (such as a for-loop body) are only accessible within that block, following the principle of local scope. Variables declared in the method but outside inner blocks remain accessible throughout the method after their declaration point. Choice D is correct because step is declared inside the for-loop block and is therefore only accessible within that block - it goes out of scope when the loop ends. Choice A is incorrect because it claims step is accessible after the loop, which violates Java's scoping rules - variables declared in a block cannot be accessed outside that block. To help students: Use visual diagrams with nested boxes to represent scope boundaries. Practice identifying where variables are declared and drawing their scope regions, emphasizing that inner declarations are not visible to outer scopes.

Question 2

In this class, which method call is valid from main? ```java public class MathUtil { private static int factorialIter(int n){ int prod = 1; for(int i=2;i<=n;i++) prod *= i; // multiply up return prod; } public static int factorial(int n){ return factorialIter(n); // delegate } }

  1. MathUtil.factorialIter(5);
  2. MathUtil.factorial(5); (correct answer)
  3. new MathUtil().factorialIter(5);
  4. factorialIter(5);

Explanation: This question tests AP Computer Science A skills, specifically the understanding of method visibility and how to call static methods with different access modifiers. In the given code, factorialIter is private static (only accessible within the class) while factorial is public static (accessible from anywhere). From main or any external location, only public methods can be called directly on the class. Choice B is correct because MathUtil.factorial(5) calls the public static method, which internally delegates to the private helper method - this is a common design pattern for exposing a clean public interface. Choice A is incorrect because it attempts to call the private method directly from outside the class, which violates access restrictions and causes a compilation error. To help students: Practice tracing method calls through public interfaces to private implementations. Use IDE features to show compilation errors when attempting to access private members, reinforcing the importance of access modifiers in API design.

Question 3

Which is the correct Java method header for an iterative factorial that returns an int and takes one int parameter?

  1. public static int factorial(int n) (correct answer)
  2. public static factorial(int n) : int
  3. public static void factorial(int n)
  4. public int factorial()

Explanation: This question tests AP Computer Science A skills, specifically the understanding of proper Java method header syntax and components. A method header in Java must specify the access modifier, static keyword (if applicable), return type, method name, and parameter list in the correct order. For a factorial method that returns an integer result and accepts an integer parameter, the header must reflect these requirements. Choice A is correct because it follows the proper syntax: public (access modifier), static (for class-level access), int (return type), factorial (method name), and (int n) (parameter). Choice C is incorrect because void indicates no return value, but factorial must return the computed result, making this a type mismatch error. To help students: Create method header templates showing the required order of components. Practice identifying and correcting method headers with missing or misplaced elements, emphasizing that return type must match what the method actually returns.

Question 4

Consider a Student class with instance variables name and grade. A method is needed to update a student's grade and return whether the update was successful (grades must be between 0 and 100 inclusive). Which method implementation correctly handles this requirement?

  1. public boolean updateGrade(int newGrade) { grade = newGrade; return true; }
  2. public boolean updateGrade(int newGrade) { if (newGrade >= 0 && newGrade <= 100) { grade = newGrade; return true; } return false; } (correct answer)
  3. public void updateGrade(int newGrade) { if (newGrade >= 0 && newGrade <= 100) { grade = newGrade; } }
  4. public boolean updateGrade(int newGrade) { if (newGrade > 0 && newGrade < 100) { grade = newGrade; return true; } return false; }

Explanation: Choice B is correct because it validates that the new grade is between 0 and 100 inclusive, updates the grade only if valid, and returns true for successful updates or false for invalid grades. Choice A is incorrect because it doesn't validate the input and always returns true. Choice C is incorrect because it doesn't return a boolean to indicate success/failure as required. Choice D is incorrect because it uses strict inequalities (> and <) instead of inclusive inequalities (>= and <=), so grades of exactly 0 or 100 would be rejected.

Question 5

A Circle class has a private instance variable radius. Which method header and implementation would be most appropriate for a method that doubles the circle's radius and returns the new area?

  1. public double doubleAndGetArea() { radius *= 2; return Math.PI * radius * radius; } (correct answer)
  2. public static double doubleAndGetArea(double radius) { radius *= 2; return Math.PI * radius * radius; }
  3. public double doubleAndGetArea() { return Math.PI * (radius * 2) * (radius * 2); }
  4. public void doubleAndGetArea() { radius *= 2; double area = Math.PI * radius * radius; }

Explanation: Choice A is correct because it modifies the instance variable radius by doubling it, then calculates and returns the new area using the updated radius value. Choice B is incorrect because static methods cannot access instance variables, and the parameter modification wouldn't affect the object's radius. Choice C is incorrect because it calculates the area as if the radius were doubled but doesn't actually modify the instance variable radius. Choice D is incorrect because it's a void method that doesn't return the calculated area, even though the method name suggests it should return a value.

Question 6

A Counter class has an instance variable count that starts at 0. Which method implementation correctly provides a way to increment the counter by a specified amount and prevent the count from exceeding a maximum value of 100?

  1. public void increment(int amount) { if (count + amount <= 100) { count += amount; } }
  2. public boolean increment(int amount) { if (count + amount <= 100) { count += amount; return true; } else { count = 100; return false; } }
  3. public boolean increment(int amount) { if (amount > 0 && count + amount <= 100) { count += amount; return true; } return false; } (correct answer)
  4. public int increment(int amount) { count += amount; if (count > 100) { count = 100; } return count; }

Explanation: Choice C is correct because it validates that the amount is positive, checks that adding it won't exceed 100, performs the increment only if both conditions are met, and returns a boolean indicating success or failure. Choice A is incorrect because it doesn't validate that amount is positive and doesn't provide feedback about whether the operation succeeded. Choice B is incorrect because when the increment would exceed 100, it sets count to 100 and returns false, which changes the count even when the operation 'fails'. Choice D is incorrect because it always performs the increment and then caps at 100, rather than preventing invalid operations.

Question 7

A Car class has instance variables make, model, and mileage. Which method correctly creates and returns a formatted string representation that would be most useful for debugging purposes?

  1. public String toString() { return make + " " + model + " (" + mileage + " miles)"; }
  2. public String display() { return "Car: " + make + " " + model + ", Mileage: " + mileage; }
  3. public String toString() { return "Car[make=" + make + ", model=" + model + ", mileage=" + mileage + "]"; } (correct answer)
  4. public void toString() { System.out.println(make + " " + model + " " + mileage); }

Explanation: Choice C is correct because it uses the standard toString() method name, returns a string (not void), and provides a detailed format showing field names and values that is most useful for debugging. The format clearly identifies each field which helps developers understand the object's state. Choice A is incorrect because while it's a proper toString() method, it doesn't clearly label the fields, making it less useful for debugging. Choice B is incorrect because it uses 'display()' instead of the standard 'toString()' method name. Choice D is incorrect because toString() should return a String, not be void and print directly.

Question 8

A BankAccount class has instance variables balance and accountNumber. Which method would be most appropriate for allowing controlled access to withdraw money, ensuring the account cannot go into negative balance?

  1. public void withdraw(double amount) { balance = balance - amount; }
  2. public double withdraw(double amount) { if (amount <= balance) { balance -= amount; } return balance; }
  3. public boolean withdraw(double amount) { if (amount > 0 && amount <= balance) { balance -= amount; return true; } return false; } (correct answer)
  4. private boolean withdraw(double amount) { if (amount <= balance && balance > 0) { balance -= amount; return true; } return false; }

Explanation: Choice C is correct because it validates that the withdrawal amount is positive and doesn't exceed the current balance, performs the withdrawal only if valid, and returns a boolean to indicate success or failure. Choice A is incorrect because it doesn't check if sufficient funds exist and could result in negative balance. Choice B is incorrect because it returns the balance even when withdrawal fails (amount > balance), which could be misleading. Choice D is incorrect because it's private (limiting access from outside the class) and the condition balance > 0 is redundant since amount <= balance already ensures sufficient funds.

Question 9

A programmer is designing a Rectangle class with instance variables length and width. Which method header would be most appropriate for a method that calculates and returns the area while ensuring the method can be called without modifying the object's state?

  1. public static double calculateArea(double length, double width)
  2. public double getArea() (correct answer)
  3. public void setArea(double area)
  4. private double area(int length, int width)

Explanation: Choice B is correct because getArea() is an instance method that can access the object's length and width instance variables to calculate and return the area without modifying the object's state. Choice A is incorrect because a static method cannot access instance variables directly. Choice C is incorrect because it's a setter method that would modify state rather than calculate area, and area should be calculated from length and width, not set independently. Choice D is incorrect because it's private (limiting access), uses int parameters instead of accessing instance variables, and doesn't follow proper naming conventions.

Question 10

A Timer class has instance variables hours, minutes, and seconds. Which method correctly advances the timer by one second, handling rollovers appropriately (60 seconds = 1 minute, 60 minutes = 1 hour)?

  1. public void tick() { seconds = (seconds + 1) % 60; if (seconds == 0) { minutes = (minutes + 1) % 60; if (minutes == 0) { hours++; } } } (correct answer)
  2. public void tick() { seconds++; if (seconds >= 60) { seconds = 0; minutes++; if (minutes >= 60) { minutes = 0; hours++; } } }
  3. public void tick() { seconds++; if (seconds == 60) { seconds = 0; minutes++; } if (minutes == 60) { minutes = 0; hours++; } }
  4. public void tick() { seconds++; if (seconds > 60) { seconds = 1; minutes++; } if (minutes > 60) { minutes = 1; hours++; } }

Explanation: When you encounter timer or counter problems in AP Computer Science A, you're dealing with modular arithmetic and cascading updates. The key challenge is ensuring that rollovers happen correctly and in the proper sequence. Let's trace through what should happen when advancing by one second. First, increment seconds. If seconds reaches 60, it should reset to 0 and minutes should increment. Similarly, if minutes reaches 60, it should reset to 0 and hours should increment. Option A handles this elegantly using the modulo operator. The expression seconds = (seconds + 1) % 60 increments seconds and automatically wraps to 0 when it reaches 60. The condition if (seconds == 0) detects when a rollover occurred, triggering the minutes increment. The same pattern applies to minutes rolling over to hours. This approach is both concise and mathematically sound. Option B has the right logic structure but uses >= comparisons, which could theoretically allow invalid states if the timer were somehow corrupted with values above the valid range. While it would work in normal circumstances, it's less robust. Option C has a critical flaw: the minutes check isn't nested inside the seconds rollover condition. This means minutes could roll over independently of seconds, breaking the cascading relationship. Option D uses > 60 instead of >= 60 or == 60, meaning seconds would need to reach 61 before rolling over. Additionally, it resets to 1 instead of 0, which is incorrect for time representation. Remember: modular arithmetic with % is often the cleanest solution for cyclical counting problems, and nested conditions ensure proper cascading behavior.

Question 11

A Book class has instance variables title, author, and pageCount. Which method would be most appropriate for comparing if two Book objects have the same content?

  1. public boolean equals(Book other) { return this.title == other.title && this.author == other.author && this.pageCount == other.pageCount; }
  2. public boolean compare(Book other) { return this.title.equals(other.title) && this.author.equals(other.author) && this.pageCount == other.pageCount; }
  3. public static boolean equals(Book book1, Book book2) { return book1.title.equals(book2.title) && book1.author.equals(book2.author); }
  4. public boolean equals(Book other) { return this.title.equals(other.title) && this.author.equals(other.author) && this.pageCount == other.pageCount; } (correct answer)

Explanation: When you encounter questions about comparing objects in Java, you need to understand the difference between reference equality and content equality, plus follow proper method conventions. The correct approach is option D because it properly overrides the equals method and uses the right comparison techniques. For the method signature, equals should be an instance method (not static) that takes the object type as a parameter. For string comparisons, you must use the .equals() method to compare actual content, not the == operator which only checks if two references point to the same object. For primitive types like int (pageCount), == is correct since it compares actual values. Option A fails because it uses == for string comparisons (title and author), which would only return true if both variables reference the exact same String object in memory, not if they contain the same text content. Option B has the wrong method name - it's called compare instead of equals. While the comparison logic is correct, this wouldn't properly override the standard equals method that Java expects for object comparison. Option C makes the method static, which is incorrect for an equals override. It also omits the pageCount comparison entirely, making it incomplete for determining if two books have the same content. Remember this pattern: when overriding equals, use .equals() for objects (especially Strings) and == for primitives. The method should be non-static and named exactly "equals" to properly override Object's equals method.

Question 12

Which code snippet correctly overloads factorial by parameter type, not by changing only the return type?

  1. int factorial(int n) { ... } long factorial(int n) { ... }
  2. int factorial(int n) { ... } int factorial(int n) { ... }
  3. int factorial(int n) { ... } int factorial(long n) { ... } (correct answer)
  4. int factorial(int n) { ... } int factorial(int n, int n) { ... }

Explanation: This question tests AP Computer Science A skills, specifically the understanding of valid method overloading in Java. Method overloading requires different parameter lists - either different types, different number of parameters, or different order of parameters. Return type alone cannot distinguish overloaded methods. Choice C is correct because it shows two factorial methods with different parameter types (int vs long), creating distinct method signatures that Java can differentiate. Choice A is incorrect because methods cannot be overloaded by return type alone - despite having different return types (int vs long), they have identical parameter lists, making them ambiguous to the compiler. To help students: Create a checklist for valid overloading: different number of parameters, different parameter types, or different parameter order. Practice identifying which method signatures would be called with various argument types.

Question 13

Which recursive factorial method includes a correct base case and returns the correct value for n0n \ge 0?

  1. public static int factorial(int n){ if(n==0) return 0; return n*factorial(n-1); }
  2. public static int factorial(int n){ if(n<=1) return 1; return n*factorial(n-1); } (correct answer)
  3. public static int factorial(int n){ if(n<=1) return 1; return factorial(n); }
  4. public static int factorial(int n){ if(n<=1) return 1; return n+factorial(n-1); }

Explanation: This question tests AP Computer Science A skills, specifically the understanding of recursive method implementation with proper base cases and recursive calls. A recursive factorial method must have a base case to stop recursion (typically when n is 0 or 1, returning 1) and a recursive case that reduces the problem size. The recursive case should multiply n by the factorial of (n-1), not add them. Choice B is correct because it has the proper base case (n<=1 returns 1) and recursive case (n * factorial(n-1)), correctly implementing the mathematical definition of factorial. Choice D is incorrect because it uses addition instead of multiplication in the recursive case, computing a sum rather than a product - this represents a conceptual error about the factorial operation. To help students: Write out the mathematical definition of factorial (n! = n × (n-1)!) and map it directly to code. Use trace tables to show how recursive calls unfold and resolve, emphasizing the importance of both correct base cases and proper operations in recursive cases.

Question 14

Which code snippet correctly demonstrates iterative factorial using a for loop and an accumulator variable in Java?

  1. int result = 0; for (int i=1;i<=n;i++) result += i; return result;
  2. int result = 1; for (int i=2;i<=n;i++) result *= i; return result; (correct answer)
  3. int result = 1; for (int i=2;i<=n;i--) result *= i; return result;
  4. int result = 1; for (int i=2;i<=n;i++) result = i; return result;

Explanation: This question tests AP Computer Science A skills, specifically the understanding of iterative algorithms using loops and accumulator variables. An iterative factorial implementation uses a loop to multiply consecutive integers, storing the running product in an accumulator variable. The accumulator must be initialized to 1 (the multiplicative identity) and the loop should multiply from 2 to n. Choice B is correct because it initializes result to 1, then uses a for loop to multiply each integer from 2 to n, properly accumulating the factorial value. Choice A is incorrect because it uses addition (+= i) instead of multiplication (*= i), calculating the sum rather than the factorial. To help students: Trace through the loop execution step-by-step, showing how the accumulator changes. Compare different loop patterns and emphasize the importance of proper initialization and operation selection.

Question 15

What is the correct syntax for defining a method that returns an integer factorial and takes one int parameter n?

  1. public int factorial(int n) { return n; } (correct answer)
  2. public factorial int(n) { return n; }
  3. public void factorial(int n) { return n; }
  4. public int factorial() { return n; }

Explanation: This question tests AP Computer Science A skills, specifically the understanding of proper Java method syntax and declaration. A method in Java must follow the pattern: access_modifier return_type method_name(parameters) { body }. The method signature includes the access modifier, return type, method name, and parameter list in the correct order. Choice A is correct because it follows the proper syntax with 'public' as the access modifier, 'int' as the return type, 'factorial' as the method name, and '(int n)' as the parameter list. Choice B is incorrect because it places 'int' after 'factorial', violating Java's syntax rules where return type must precede the method name. To help students: Use syntax diagrams and color-coding to highlight each component of a method declaration. Practice writing method headers before implementing the body, emphasizing the importance of correct ordering.

Question 16

Which code snippet correctly uses a base case in recursive factorial to prevent infinite recursion in Java?

  1. if (n == 0) return 1; else return n * factorial(n - 1); (correct answer)
  2. if (n == 0) return 1; else return n * factorial(n + 1);
  3. if (n == 0) break; else return n * factorial(n - 1);
  4. if (n = 0) return 1; else return n * factorial(n - 1);

Explanation: This question tests AP Computer Science A skills, specifically the understanding of base cases in recursive methods to prevent infinite recursion. A base case is a condition that stops the recursive calls and returns a value directly, essential for proper recursion termination. In factorial calculation, the base case is when n equals 0 (or 1), where factorial is defined as 1. Choice A is correct because it properly checks if n equals 0 using the equality operator (==) and returns 1, otherwise makes a recursive call with n-1. Choice D is incorrect because it uses the assignment operator (=) instead of the equality operator (==), which would assign 0 to n rather than comparing values. To help students: Emphasize the difference between = (assignment) and == (comparison) operators. Practice tracing recursive calls to show how the base case prevents stack overflow and ensures proper termination.

Question 17

Which parameter type is appropriate for convertTemperature when converting Celsius to Fahrenheit and returning a decimal result?

  1. int, because temperatures never need fractional values.
  2. double, because the formula can produce decimals. (correct answer)
  3. String, because inputs are read as text in Java.
  4. boolean, because conversion is a true/false decision.

Explanation: This question tests AP Computer Science A skills, specifically the understanding of appropriate data types for method parameters and return values. When converting temperatures between Celsius and Fahrenheit, the formula (C × 9/5 + 32) involves division and can produce fractional results. The double data type in Java can store decimal values with high precision, making it suitable for temperature calculations. Choice B is correct because double accommodates the decimal results that temperature conversions typically produce, ensuring accuracy in calculations. Choice A is incorrect because using int would truncate decimal values, leading to loss of precision in temperature conversions. To help students: Demonstrate the difference between integer and floating-point arithmetic with concrete examples. Show how using int for temperature conversion could lead to significant errors, especially in scientific applications.

Question 18

Which snippet correctly shows an iterative factorial method using a loop and accumulator variable, returning an int?

  1. public static int factorial(int n){ int p=1; for(int i=2;i<=n;i++) p*=i; return p; } (correct answer)
  2. public static int factorial(int n){ int p=0; for(int i=2;i<=n;i++) p*=i; return p; }
  3. public static int factorial(int n){ for(int i=2;i<=n;i++) return i; }
  4. public static int factorial(int n){ while(n>1){ n--; } return n; }

Explanation: This question tests AP Computer Science A skills, specifically the understanding of iterative method implementation with proper initialization and loop structure. An iterative factorial method uses a loop to multiply consecutive integers and requires correct initialization of the accumulator variable. The accumulator must start at 1 (multiplicative identity) not 0, and the loop must iterate through all necessary values. Choice A is correct because it initializes the accumulator p to 1 and uses a for loop to multiply all integers from 2 to n, correctly computing the factorial. Choice B is incorrect because it initializes p to 0, causing all multiplications to result in 0 regardless of input - this is a common initialization error when students confuse additive identity (0) with multiplicative identity (1). To help students: Emphasize the importance of choosing correct initial values based on the operation (1 for multiplication, 0 for addition). Trace through small examples by hand to show how incorrect initialization propagates through the entire calculation.

Question 19

A Temperature class stores temperature in Celsius. Which method correctly converts the stored Celsius temperature to Fahrenheit using the formula F = (9/5)C + 32?

  1. public double toFahrenheit() { return celsius * 9 / 5 + 32; }
  2. public void toFahrenheit() { celsius = (9 / 5) * celsius + 32; }
  3. public static double toFahrenheit(double celsius) { return 9 / 5 * celsius + 32; }
  4. public double toFahrenheit() { return (9.0 / 5.0) * celsius + 32; } (correct answer)

Explanation: When you encounter method design questions in AP Computer Science A, pay attention to three key elements: the method's return type, how it handles data, and potential pitfalls with integer division. The correct answer is D because it properly implements the temperature conversion formula while avoiding Java's integer division trap. The formula F = (9/5)C + 32 requires decimal arithmetic, and option D uses 9.0 / 5.0 to ensure floating-point division, which gives the correct result of 1.8. The method returns a double value without modifying the original celsius field, which is appropriate for a conversion method. Let's examine why the other options fail: Option A uses integer division 9 / 5, which evaluates to 1 instead of 1.8 in Java. This would produce incorrect temperature conversions. Option B has a void return type and modifies the original celsius field. This destroys the original temperature data and doesn't return the converted value, making it poorly designed for a conversion method. Option C makes the method static, but then tries to use a parameter named celsius instead of accessing an instance field. While the logic might work, it doesn't fit the context of a Temperature class that "stores temperature in Celsius" as an instance variable. Key takeaway: Always use floating-point literals (like 9.0 and 5.0) when you need decimal division in Java. Integer division truncates the decimal portion, which is a common source of bugs in mathematical calculations.