Scope and Access

AP Computer Science A· difficulty 3/5

public class Demo {
    private int x = 10;
    public int compute() {
        int x = 5;
        return x;
    }
}
// ...
Demo d = new Demo();
System.out.println(d.compute());

What is printed?

  • A

    15

  • B

    10

  • C

    5

    check_circle
  • D

    Compile-time error

Explanation

The local variable x shadows the instance variable inside compute, so the local x with value 5 is returned.

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

Related questions