Static Variables and Methods

AP Computer Science A· difficulty 3/5

public class Bug {
    private int x;
    public static int y;
    public void doIt() {
        x++;
        y++;
    }
}
// ...
Bug b1 = new Bug();
Bug b2 = new Bug();
b1.doIt(); b1.doIt(); b2.doIt();
System.out.println(Bug.y);

What is printed?

  • A

    0

  • B

    1

  • C

    2

  • D

    3

    check_circle

Explanation

The static variable y is shared across all instances; doIt was called 3 times total, so y is 3.

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

Related questions