Objects and References
Explain object creation, references, null, aliases, object state, method invocation, and reference versus primitive behavior.
A lesson of AP Computer Science A, in Objects and Classes, about 10 minutes.
By the end of this lesson, you will be able to explain the difference between primitive variables and object references, understand null, and explain aliasing.
Primitives vs. References
int x = 5; // the variable x contains the value 5
int y = x; // y gets a COPY of 5
y = 10; // changing y does NOT affect x
// x is still 5
Primitive variable: stores the actual value directly in the variable.
Reference variable: stores the MEMORY ADDRESS of an object, not the object itself.
Dog d1 = new Dog("Rex"); // d1 stores the address of the Dog object
Dog d2 = d1; // d2 stores the SAME address
d2.setName("Buddy"); // changes the SAME object
// d1.getName() is now "Buddy"!
This is aliasing — two variables pointing to the same object. Changes through one reference are visible through the other.
The new Keyword
Dog myDog = new Dog("Rex", 3);
new:
- Allocates memory on the heap for the object
- Calls the constructor to initialize the object
- Returns the memory address, which is stored in
myDog
null
Dog d = null; // d doesn't point to any Dog
d.getName(); // NullPointerException! Can't call methods on null
if (d != null) {
d.getName(); // Safe — check before using
}
null: a special reference value meaning "this variable doesn't point to any object."
Uninitialized object references default to null. Always check before using a reference that might be null.
Comparing Objects
String s1 = new String("hello");
String s2 = new String("hello");
s1 == s2 // FALSE — different objects in memory
s1.equals(s2) // TRUE — same content
== for objects: tests if two references point to the SAME object in memory.
.equals() for objects: tests if two objects have the same content (if the class defines equals()).
For classes you write: if you don't override equals(), it defaults to reference equality (same as ==).
Object Lifecycle
- Declaration: — reference variable exists; currently holds