AP Computer Science A · Topic 5.6

Writing Methods Practice

Part of Writing Classes.

Practice questions

28

Want a predicted score for the whole AP CSA exam? Take the 20-question diagnostic and Lumi will plan the rest.

Sample questions

5 of 28 — sign in to practice the rest with adaptive difficulty and mastery tracking.

  1. Sample 1difficulty 1/5

    public class C {
        public double computeAverage(int[] nums) {
            return 0.0;
        }
    }
    // ...

    Which is the method's signature?

    • A

      computeAverage(int[])

      check_circle
    • 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.

  2. 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

    • D

      0

      check_circle

    Why

    n is 0, so neither if branch returns; the final return 0 executes.

  3. 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?

    • A

      Got K(7)

      check_circle
    • B

      Compile-time error

    • C

      Got 7

    • D

      Got K

    Why

    String concatenation invokes toString on the object, producing "Got K(7)".

  4. 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

    • C

      Return type must be boolean to match the expression n > 0

      check_circle
    • 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.

  5. 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?

    • A

      return b;

      check_circle
    • 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.