AP Computer Science A · Topic 5.7
Static Variables and Methods Practice
Part of Writing Classes.
Practice questions
26
Sample questions
5 of 26 — sign in to practice the rest with adaptive difficulty and mastery tracking.
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?
- Acheck_circle
105 then 5
- 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.
- A
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?
- Acheck_circle
36
- B
12
- C
6
- D
Compile-time error
Why
Static methods are called on the class. square(6) returns 36.
- A
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?
- Acheck_circle
14
- 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.
- A
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?
- Acheck_circle
12.56636
- B
6.28318
- C
3.14159
- D
Compile-time error
Why
area is PI * 2 * 2 = 3.14159 * 4 = 12.56636.
- A
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
- Dcheck_circle
300
Why
The static factory invokes the private constructor with 300, which is stored in cents.
- A