References, equality, identity

An object variable is a reference: null, aliases, identity (==) versus equality (equals), a redefined equals, shallow or deep copy, in Java.

  • 27 cards
  • 4 topics
  • Free

The outline, topic by topic

Each topic is weighted the way the exam weighs it.

  1. Concepts
  2. Questions
  3. Sort and link
  4. Understand

A few cards from the deck

  • Reference: what is it?

    Show the answer

    The value stored in an object variable, which tells where the object sits in memory.

    Point b = a; copies the reference, not the object: a and b then designate the same point.

  • What are a.x and c.x at the end of this program?

    ```java
    Point a = new Point(1, 2);
    Point b = a;
    Point c = new Point(1, 2);
    b.x = 5;
    `

    • 5 and 1
    • 1 and 1
    • 5 and 5
    • 1 and 5
    Show the answer

    5 and 1

    b is an alias of a: the same object, so a.x becomes 5. c is a second object created with the same values: it does not change.

  • A variable of object type does not hold the object itself but a … to it.

    Show the answer

    A variable of object type does not hold the object itself but a reference to it.

    Primitive types (int, boolean…) store their value directly; all the others go through a reference.

  • null: what is it?

    Show the answer

    The reference value that designates no object.

    Reading an attribute or calling a method through null raises NullPointerException.

  • Why is a.equals(c) false when Point has not redefined equals, even if a and c have the same coordinates?

    • equals only applies to strings
    • The equals of Object compares references, like ==
    • The coordinates are ints, which equals cannot read
    • Two separately created objects are never equal in Java
    Show the answer

    The equals of Object compares references, like ==

    The class must say what equality of two points means. Once equals(Object o) is redefined to compare x and y, a.equals(c) becomes true, while a == c stays false.