Static Variables and Methods

AP Computer Science A· difficulty 4/5

public class K {
    static int s = 0;
    int v;
    public K(int v) { this.v = v; s += v; }
    public int total() { return s + v; }
}
public static int run() {
    K a = new K(2);
    K b = new K(3);
    K c = new K(4);
    return a.total() + b.total();
}
// Call: System.out.println(run());

What is printed?

  • A

    23

    check_circle
  • B

    18

  • C

    27

  • D

    20

Explanation

After all constructions s=2+3+4=9. a.total()=9+2=11. b.total()=9+3=12. Sum=23.

Want 10 more like this — adaptive to your weak spots?

Related questions