Mutator Methods

AP Computer Science A· difficulty 4/5

public class P {
    int x;
    public P(int x) { this.x = x; }
}
public static void update(P p) {
    p.x = p.x + 10;
    p = new P(0);
    p.x = 99;
}
public static int run() {
    P a = new P(5);
    update(a);
    return a.x;
}
// Call: System.out.println(run());

What is printed?

  • A

    0

  • B

    15

    check_circle
  • C

    99

  • D

    5

Explanation

p.x = p.x+10 mutates a's x to 15. Reassigning p locally doesn't affect a.

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

Related questions