AP Computer Science A · Study guide

Object Reference Comparisons

AP® Computer Science A · Selection and Iteration

Comparing Object References

Using == and != to tell whether two variables share an object, comparing references with null to find out whether an object exists, and using a class's equals method to decide whether two objects are equivalent.

Big Picture

Two different variables can hold references to the same object. Object references can be compared using == and !=, which ask whether two variables refer to the same object. An object reference can be compared with null to determine if it actually references an object. Whether two different objects should count as equal is a separate question: classes often define their own equals method, which specifies the criteria for equivalency, most often using attributes of the two objects.

1Same Object or Just the Same Contents?

When comparing objects, there are two very different questions. The first is about identity: are these two variables referring to the very same object? The second is about equivalence: do these two objects, which may be separate, represent the same value? Two plants created separately with the same species and height are equivalent in contents but are not the same object.

The difference matters because of aliasing. If two variables refer to the same object, a change made through one is visible through the other. If they refer to two separate objects, changes to one leave the other untouched. Knowing which situation you are in is essential for predicting what code does.

Aliases arise in ordinary ways: assigning one reference variable to another, passing an object to a method (the parameter becomes an alias of the argument), or storing a reference in two places. Separate objects arise only from separate new expressions or from methods that build new objects, such as substring. Counting where objects are created tells you how many distinct objects exist.

Figure 1. Two different variables can hold references to the same object. == is true only for such aliases, not for separate objects with matching contents.
ComparisonAsksExample result
a == bDo a and b refer to the same object?false for two separate objects with equal contents
a != bDo they refer to different objects?true for two separate objects
a == nullDoes a refer to no object?true when a holds null
a != nullDoes a refer to an object?true when a holds a reference
a.equals(b)Are the objects equivalent by the class's criteria?true for two Strings with the same characters
Worked Example 1 Aliases

Two Variables, One Plant

The Plant class is given. Predict the output.

The Plant class and a short program
public class Plant
{
    private String species;
    private int height;

    public Plant(String s, int h)
    {
        species = s;
        height = h;
    }

    public void grow(int cm)
    {
        height = height + cm;
    }

    public String getSpecies()
    {
        return species;
    }

    public int getHeight()
    {
        return height;
    }

    /** Returns true if this plant and other are the same species. */
    public boolean sameSpeciesAs(Plant other)
    {
        return species.equals(other.getSpecies());
    }
}
Output
false
true
35 30
  1. 1a == b. Two new expressions created two objects: false, even though their contents match.
  2. 2a == c. c holds the same reference as a: true.
  3. 3c.grow(5) changes the object that a and c share, so a.getHeight() is 35; b's separate object is still 30.
Result: The output is false, true, and 35 30. Two different variables can hold references to the same object, and == is true exactly for such aliases.

2== and != on References

Object references can be compared using == and !=. With reference types, these operators compare the references themselves: a == b is true exactly when a and b refer to the same object, and a != b is true when they refer to different objects. The objects' attributes play no part in the comparison.

Because the result depends only on which object each variable refers to, it changes whenever a variable is reassigned. Tracing reference comparisons means tracking, statement by statement, which object each variable refers to. A table with one column per variable, as below, keeps this clear; remember that each new creates a different object and each assignment between variables creates an alias.

Statementx refers toy refers tox != y
Plant x = new Plant("mint", 9);object 1(not declared)
Plant y = x;object 1object 1false
y = new Plant("mint", 9);object 1object 2true
x = y;object 2object 2false
Worked Example 2 != with references

Tracking When References Change

Predict the output.

Using the same Plant class
public class Plant
{
    private String species;
    private int height;

    public Plant(String s, int h)
    {
        species = s;
        height = h;
    }

    public void grow(int cm)
    {
        height = height + cm;
    }

    public String getSpecies()
    {
        return species;
    }

    public int getHeight()
    {
        return height;
    }

    /** Returns true if this plant and other are the same species. */
    public boolean sameSpeciesAs(Plant other)
    {
        return species.equals(other.getSpecies());
    }
}
Output
false
true
false
  1. 1First check. y is an alias for x: same reference, so x != y is false.
  2. 2After y = new Plant(...). y refers to a new object: true.
  3. 3After x = y. Both refer to the second object again: false.
Result: The output is false, true, false. != on references is true whenever the variables refer to different objects, and its value changes as variables are reassigned.
Common Mistake 1 · Expecting == to Compare Contents

new Plant("fern", 30) == new Plant("fern", 30) is false. With objects, == never looks inside; it only checks whether both sides are the same object. To compare contents, use a method the class provides for that purpose.

3Comparing With null

An object reference can be compared with null, using == or !=, to determine if the reference actually references an object. p != null is true when p refers to an object, and p == null is true when it refers to nothing. This is exactly the right tool, since null is a reference value.

The most common use is protection: before calling a method through a reference that might be null, check it first, either with an if statement or on the left side of && so that short-circuit evaluation skips the call. Variables that start as null and receive an object later, such as "the tallest plant measured so far," are typically checked this way.

A null check is a reference comparison, so it never calls any method and can never throw an exception itself. It is always safe to evaluate, which is what makes it a reliable guard. By contrast, any expression that uses the dot operator on a reference, such as p.getHeight() or p.equals(q), is only safe once the reference is known to be non-null.

Figure 2. An object reference can be compared with null, using == or !=, to determine if it actually references an object.
Worked Example 3 Comparing with null

Checking Before Using

Predict the output.

Using the same Plant class
public class Plant
{
    private String species;
    private int height;

    public Plant(String s, int h)
    {
        species = s;
        height = h;
    }

    public void grow(int cm)
    {
        height = height + cm;
    }

    public String getSpecies()
    {
        return species;
    }

    public int getHeight()
    {
        return height;
    }

    /** Returns true if this plant and other are the same species. */
    public boolean sameSpeciesAs(Plant other)
    {
        return species.equals(other.getSpecies());
    }
}
Output
nothing measured yet
bamboo 120
  1. 1First check. tallest holds null, so tallest == null is true.
  2. 2After assignment, tallest refers to an object, so tallest != null is true and calling its methods is safe.
Result: The output is nothing measured yet, then bamboo 120. Comparing a reference with null determines whether it actually references an object.
Common Mistake 2 · Checking for null After Using the Reference

p.getHeight() > 10 && p != null calls the method before the check, so a null reference still causes a NullPointerException. The null check must come first.

4Equivalence and the equals Method

Classes often define their own equals method, which can be used to specify the criteria for equivalency for two objects of the class. The equivalency of two objects is most often determined using attributes from the two objects. For String, the criteria are the characters: two strings are equals when they contain the same sequence of characters, even if they are different objects.

Each class's author decides what "equivalent" means for that class. Two calendar dates might be equivalent when their year, month, and day match; two plants might be considered the same kind when their species match, whatever their heights. A class's documentation states its criteria. The Plant class in the examples expresses its species criterion through a method named sameSpeciesAs, which compares one attribute using String's equals.

Figure 3. Classes often define their own equals method, which specifies the criteria for equivalency of two objects, most often using their attributes.
Worked Example 4 String equality

== Versus equals on Strings

Predict the output.

Code
String place = "seaside";
String start = place.substring(0, 3);
String word = "sea";
System.out.println(start);
System.out.println(start == word);
System.out.println(start.equals(word));
Output
sea
false
true
  1. 1substring builds a new object containing "sea".
  2. 2start == word. Different objects: false, even though both print as sea.
  3. 3start.equals(word). The String class's equals compares the sequence of characters: true.
Result: The output is sea, false, true. For strings, equals applies the class's own criteria for equivalence: the same characters in the same order.
Worked Example 5 Class-defined criteria

Comparing by Attributes

The Plant class provides sameSpeciesAs, which compares species. Predict the output.

Using the same Plant class
public class Plant
{
    private String species;
    private int height;

    public Plant(String s, int h)
    {
        species = s;
        height = h;
    }

    public void grow(int cm)
    {
        height = height + cm;
    }

    public String getSpecies()
    {
        return species;
    }

    public int getHeight()
    {
        return height;
    }

    /** Returns true if this plant and other are the same species. */
    public boolean sameSpeciesAs(Plant other)
    {
        return species.equals(other.getSpecies());
    }
}
Output
false
true
false
  1. 1p1 == p2. Separate objects: false.
  2. 2p1.sameSpeciesAs(p2). The method compares one attribute, the species string, using equals: both are "basil", so true, even though the heights differ.
  3. 3p1.sameSpeciesAs(p3). "basil" versus "thyme": false.
Result: The output is false, true, false. A class decides which attributes make two of its objects equivalent; here, matching species is the criterion, and height does not matter.
Common Mistake 3 · Comparing Strings With ==

A string built by substring, concatenation, or a constructor is a new object. Comparing it with == to another string with the same characters gives false. Use equals whenever the question is about characters.

5Calling equals Safely

A call such as answer.equals("yes") is a method call through answer, so it throws a NullPointerException if answer is null. There are two standard safe forms. Calling equals on the literal, "yes".equals(answer), works because the literal is never null, and comparing it with a null argument simply returns false. Alternatively, guard the call: answer != null && answer.equals("yes").

Both forms give the same results whenever answer refers to a string, and both handle null without failing. Choose the guarded form when the code needs to do more with answer after the check, and the literal-first form for a quick one-time test.

The same reasoning applies to any class's comparison methods, not only equals. A call such as p1.sameSpeciesAs(p2) needs p1 to refer to an object, and, because the method calls other.getSpecies(), it needs p2 to refer to one as well. Reading a method's code or documentation tells you which references must be non-null for the call to work; that requirement is a precondition the caller must meet.

Expressionanswer is nullanswer is "yes"
"yes".equals(answer)falsetrue
answer != null && answer.equals("yes")falsetrue
answer.equals("yes")NullPointerExceptiontrue
answer == "yes"falsenot reliable: compares references
Worked Example 6 null and equals

Which Side Calls equals?

The variable answer may be null. Compare the two ways of writing the test.

Safe forms
String answer = null;
System.out.println("yes".equals(answer));
System.out.println(answer != null && answer.equals("yes"));
Output
false
false
Unsafe form
String answer = null;
System.out.println(answer.equals("yes"));
  1. 1"yes".equals(answer). The method is called on the literal, which is never null; comparing with a null argument returns false.
  2. 2Guarded form. answer != null is false, so && short-circuits and equals is never called.
  3. 3Unsafe form. Calling equals through a null reference throws a NullPointerException.
Result: The safe forms print false twice; the unsafe form stops with a NullPointerException. Either call equals on a value known to exist, or check for null first.

6Choosing the Right Comparison

Every object comparison answers one of three questions. "Are these the same object?" calls for == or !=. "Do these objects represent equivalent values?" calls for the class's equals method or another comparison method it provides. "Is there an object at all?" calls for comparing with null. Picking the operator before identifying the question is the source of most mistakes.

In practice, equivalence is the question most programs need for strings, so equals is the usual choice there. Identity checks with == are appropriate when aliasing itself is the point, such as confirming that two variables refer to the same object before changing it, and null checks protect every method call on a reference that might be empty.

Figure 4. Decide which question you are asking before choosing between ==, !=, and equals.
Common Mistake 4 · Using equals to Ask About Identity

If the question is whether a change through one variable will be seen through another, equals is the wrong test: two equivalent but separate objects will report true, yet changing one does not affect the other. Only == answers whether two variables share an object.

Four Habits for Comparing Objects

1. == Means Same Object

It never compares attributes.

2. Check null First

Guard every method call on a reference that may be null.

3. equals for Equivalence

The class's criteria, usually its attributes, decide.

4. Literal First

"yes".equals(answer) cannot throw on null.

Core Synthesis

Two different variables can hold references to the same object, and object references can be compared using == and !=. An object reference can be compared with null, using == or !=, to determine if the reference actually references an object. Classes often define their own equals method, which can be used to specify the criteria for equivalency for two objects of the class; the equivalency of two objects is most often determined using attributes from the two objects.