Methods: How to Write Them
Help Questions
AP Computer Science A › Methods: How to Write Them
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.
step is accessible only inside the for-loop block where declared.
i is accessible after the for-loop because it is an int.
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.
Which code snippet correctly overloads factorial by parameter type, not by changing only the return type?
int factorial(int n) { ... } int factorial(int n) { ... }
int factorial(int n) { ... } int factorial(int n, int n) { ... }
int factorial(int n) { ... } int factorial(long n) { ... }
int factorial(int n) { ... } long factorial(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.
Which code snippet correctly demonstrates iterative factorial using a for loop and an accumulator variable in Java?
int result = 1; for (int i=2;i<=n;i++) result *= i; return result;
int result = 1; for (int i=2;i<=n;i--) result *= i; return result;
int result = 0; for (int i=1;i<=n;i++) result += i; return result;
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.
Which code snippet correctly uses a base case in recursive factorial to prevent infinite recursion in Java?
if (n == 0) return 1; else return n * factorial(n - 1);
if (n == 0) break; else return n * factorial(n - 1);
if (n = 0) return 1; else return n * factorial(n - 1);
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.
Which parameter type is appropriate for convertTemperature when converting Celsius to Fahrenheit and returning a decimal result?
double, because the formula can produce decimals.
int, because temperatures never need fractional values.
boolean, because conversion is a true/false decision.
String, because inputs are read as text in Java.
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.
What is the correct syntax for defining a method that returns an integer factorial and takes one int parameter n?
public int factorial() { return n; }
public int factorial(int n) { return n; }
public void factorial(int n) { return n; }
public factorial int(n) { 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.
Which recursive factorial method includes a correct base case and returns the correct value for $n \ge 0$?
public static int factorial(int n){ if(n<=1) return 1; return factorial(n); }
public static int factorial(int n){ if(n<=1) return 1; return n*factorial(n-1); }
public static int factorial(int n){ if(n<=1) return 1; return n+factorial(n-1); }
public static int factorial(int n){ if(n==0) return 0; 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.
Which snippet correctly shows an iterative factorial method using a loop and accumulator variable, returning an int?
public static int factorial(int n){ while(n>1){ n--; } return n; }
public static int factorial(int n){ int p=0; for(int i=2;i<=n;i++) p*=i; return p; }
public static int factorial(int n){ int p=1; for(int i=2;i<=n;i++) p*=i; return p; }
public static int factorial(int n){ for(int i=2;i<=n;i++) return i; }
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.
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
}
}
new MathUtil().factorialIter(5);
MathUtil.factorialIter(5);
MathUtil.factorial(5);
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.
Which is the correct Java method header for an iterative factorial that returns an int and takes one int parameter?
public static void factorial(int n)
public static int factorial(int n)
public static factorial(int n) : int
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.