AP Computer Science A · Topic 5.7

Static Variables and Methods Practice

Part of Writing Classes.

Practice questions

26

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 26 — sign in to practice the rest with adaptive difficulty and mastery tracking.

  1. Sample 1difficulty 2/5

    public class Util {
        public static int base = 100;
        public static int boost(int x) {
            return base + x;
        }
    }
    // ...
    System.out.println(Util.boost(5));
    Util.base = 0;
    System.out.println(Util.boost(5));

    What is printed?

    • A

      105 then 5

      check_circle
    • B

      5 then 5

    • C

      Compile-time error

    • D

      105 then 105

    Why

    First call uses base=100 returning 105; after setting base to 0, the second call returns 5.

  2. Sample 2difficulty 2/5

    public class MathUtil {
        public static int square(int n) { return n * n; }
    }
    // ...
    System.out.println(MathUtil.square(6));

    What is printed?

    • A

      36

      check_circle
    • B

      12

    • C

      6

    • D

      Compile-time error

    Why

    Static methods are called on the class. square(6) returns 36.

  3. Sample 3difficulty 2/5

    public class Util {
        public static int doubleIt(int n) { return n * 2; }
    }
    // ...
    Util u = new Util();
    System.out.println(u.doubleIt(7));

    What is printed?

    • A

      14

      check_circle
    • B

      7

    • C

      Compile-time error

    • D

      0

    Why

    Although calling a static method through an instance is discouraged, it compiles; the method returns 14.

  4. Sample 4difficulty 2/5

    public class Circle {
        public static final double PI = 3.14159;
        private double r;
        public Circle(double r) { this.r = r; }
        public double area() { return PI * r * r; }
    }
    // ...
    Circle c = new Circle(2);
    System.out.println(c.area());

    What is printed?

    • A

      12.56636

      check_circle
    • B

      6.28318

    • C

      3.14159

    • D

      Compile-time error

    Why

    area is PI * 2 * 2 = 3.14159 * 4 = 12.56636.

  5. Sample 5difficulty 3/5

    public class Money {
        private int cents;
        private Money(int c) { cents = c; }
        public static Money fromDollars(int d) {
            return new Money(d * 100);
        }
        public int getCents() { return cents; }
    }
    // ...
    Money m = Money.fromDollars(3);
    System.out.println(m.getCents());

    What is printed?

    • A

      3

    • B

      100

    • C

      Compile-time error

    • D

      300

      check_circle

    Why

    The static factory invokes the private constructor with 300, which is stored in cents.