AP Computer Science A · Topic 5.9

this Keyword Practice

Part of Writing Classes.

Practice questions

10

Want a predicted score for the whole AP CSA exam? Take the 20-question diagnostic and Lumi will plan the rest.

Sample questions

5 of 10 — sign in to practice the rest with adaptive difficulty and mastery tracking.

  1. Sample 1difficulty 2/5

    public class Person {
        private String name;
        public Person(String name) {
            name = name;
        }
        public String getName() { return name; }
    }
    // ...
    Person p = new Person("Bo");
    System.out.println(p.getName());

    What is printed?

    • A

      null

      check_circle
    • B

      Bo

    • C

      name

    • D

      Compile-time error

    Why

    Without this.name = name the assignment only sets the parameter to itself; the instance variable name remains its default null.

  2. Sample 2difficulty 2/5

    public class Pair {
        private int a, b;
        public Pair(int a, int b) {
            this.a = a;
            this.b = b;
        }
        public int sum() { return a + b; }
    }
    // ...
    Pair p = new Pair(3, 4);
    System.out.println(p.sum());

    What is printed?

    • A

      7

      check_circle
    • B

      0

    • C

      12

    • D

      Compile-time error

    Why

    this.a and this.b are set to 3 and 4; sum returns 7.

  3. Sample 3difficulty 3/5

    public class Point {
        private int x, y;
        public Point(int x, int y) {
            /* missing */
            this.y = y;
        }
    }

    Which line replaces /* missing */?

    • A

      this.x = this.x;

    • B

      x = x;

    • C

      this.x = x;

      check_circle
    • D

      x = this.x;

    Why

    Use this.x to refer to the field shadowed by the parameter; otherwise the assignment is parameter-to-itself.

  4. Sample 4difficulty 3/5

    public class Box {
        private int width;
        public Box(int width) {
            width = width;
        }
    }

    What is wrong with the constructor?

    • A

      Nothing is wrong

    • B

      private fields cannot be set in a constructor

    • C

      The parameter shadows the field; assignment has no effect on the field

      check_circle
    • D

      Constructors cannot have parameters

    Why

    The parameter width shadows the instance field of the same name. The assignment width = width copies the parameter to itself; it should be this.width = width.

  5. Sample 5difficulty 3/5

    public class A {
        public A() {
            System.out.print("hi ");
            this(5);
        }
        public A(int n) {}
    }
    // ...

    What is the result?

    • A

      Nothing is printed

    • B

      Run-time error

    • C

      Compile-time error: this(...) must be the first statement

      check_circle
    • D

      hi printed

    Why

    A call to this(...) (or super(...)) must appear as the very first statement of a constructor.