Objects and References

intermediate85 min

References in memory

A variable for an object type stores a reference to the object in memory, not the object bytes themselves. Assigning one variable to another copies the reference, so both names can refer to the same object.

Creating a reference

Assignment copies the reference

robot2 = robot1 does not clone the object. Both variables point at the same instance.

Assignment example

The null reference

null means the variable does not point at any object. Calling a method on null throws NullPointerException.

null example

Avoiding NullPointerException

  • Always Check: Use if (object != null) before calling methods
  • Initialize Variables: Give object variables initial values when possible
  • Defensive Programming: Validate parameters in methods that receive objects
  • Read Error Messages: NullPointerException tells you which line caused the error
  • Use Debugging: Print object values to see which ones are null

Objects as Method Parameters

Objects can be passed as parameters to methods, just like primitive values. Since objects are passed by reference, the method receives a copy of the reference, not a copy of the object. This means the method can modify the original object.

Objects as parameters

Objects as Return Values

Methods can also return objects. This is useful for creating factory methods, cloning objects, or building new objects based on existing ones. The method returns a reference to the object, which can then be assigned to a variable.

Methods returning objects

Object Equality and the equals() Method

By default, Java compares objects using reference equality (==), which checks if two variables point to the same object in memory. However, you often want to compare objects based on their content. This is where the equals() method comes in. You can override this method to define what makes two objects ‘equal’ based on their properties.

Implementing equals()

Object Equality and Collections

The equals() method is crucial when working with collections like ArrayList. Methods like contains(), indexOf(), and remove() use the equals() method to find objects in the collection. Without a proper equals() implementation, these methods won’t work as expected.

Objects in collections

Try It Yourself:

Practice with Objects and References

  • Create a Sensor class with equals() method that compares sensor type and ID
  • Build a Robot class that can be safely cloned with all its sensor references
  • Design a Competition class that manages teams and handles null robot references safely
  • Create a method that finds robots with low battery levels in a team roster
Test your understanding of object references, null handling, and object equality: