Static Variables and Methods

AP Computer Science A· difficulty 3/5

public class Bad {
    private int x = 5;
    public static int getX() {
        return x;
    }
}
// ...
System.out.println(Bad.getX());

What is the result?

  • A

    Compile-time error

    check_circle
  • B

    5

  • C

    0

  • D

    Run-time error

Explanation

A static method cannot reference an instance variable directly because no instance exists in a static context.

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

Related questions