COMP 210: Data Structures

Review of References


In Java, a reference is a variable that stores the memory address of an object, not the object itself. Think of it as a pointer or a handle to an object, similar to how a street address pornts to a specific house. You use this reference to access the object’s methods and fields. Actual objects are created with the new keyword, and can then be assigned to a reference variable. If a reference variable has not yet been assigned an object, it is a null reference.

    MyObject obj;          // Creates a null reference, no object
    obj = new MyObject();  // Creates an object; obj now refers to it
    obj.myMethod();
    obj.myField = 10;

Primitive Types vs. References

It’s crucial to understand the difference between how Java handles primitive types (like int, double, boolean) and reference types (all classes, including String). When a variable of a primitive type is defined, space in memory is set aside for a value of that type. On the other hand, when a variable of a class type is defined, that merely creates space in memory for a reference to an object of that type, but not for the object itself. No space is created for the actual object until you use the new keyword, invoking the constructor and initializing the object.


Copied Values vs. Aliases


Null References

A reference variable holds the special value null when it doesn’t point to any object at all.

    MyObject nullObj1;
    MyObject nullObj2 = null;

If you try to call a method or access a field on a null reference, you’ll get a NullPointerException at runtime. This is a very common error for students to encounter. It’s a key part of memory management in Java and is a frequent topic in debugging.