AP Computer Science A · Topic 5.6
Writing Methods Practice
Part of Writing Classes.
Practice questions
28
Sample questions
5 of 28 — sign in to practice the rest with adaptive difficulty and mastery tracking.
Sample 1difficulty 1/5
public class C { public double computeAverage(int[] nums) { return 0.0; } } // ...Which is the method's signature?
- Acheck_circle
computeAverage(int[])
- B
public double computeAverage(int[] nums)
- C
double computeAverage
- D
computeAverage()
Why
A method's signature consists of its name and parameter types only, not return type or modifiers.
- A
Sample 2difficulty 2/5
public class Tester { public int sign(int n) { if (n > 0) return 1; if (n < 0) return -1; return 0; } } // ... Tester t = new Tester(); System.out.println(t.sign(0));What is printed?
- A
Compile-time error
- B
-1
- C
1
- Dcheck_circle
0
Why
n is 0, so neither if branch returns; the final return 0 executes.
- A
Sample 3difficulty 2/5
public class K { private int n; public K(int n) { this.n = n; } public String toString() { return "K(" + n + ")"; } } // ... K k = new K(7); System.out.println("Got " + k);What is printed?
- Acheck_circle
Got K(7)
- B
Compile-time error
- C
Got 7
- D
Got K
Why
String concatenation invokes toString on the object, producing "Got K(7)".
- A
Sample 4difficulty 2/5
public static int isPositive(int n) { return n > 0; }What is wrong?
- A
The method must be void
- B
Nothing is wrong
- Ccheck_circle
Return type must be boolean to match the expression n > 0
- D
n must be checked with .equals
Why
n > 0 yields a boolean; an int return type produces a compile error. Change the type to boolean.
- A
Sample 5difficulty 2/5
public static int max(int a, int b) { if (a > b) { return a; } // line 4 }What must be added at line 4 to make the method compile and work?
- Acheck_circle
return b;
- B
Nothing; the code compiles as is
- C
break;
- D
return 0;
Why
Java requires every code path of a non-void method to return a value. When a <= b, no return executes, so the method must return b.
- A