In this short tutorial, we’ll look at the differences between objects and references in Java.
Object in Java
An object is an instance of a class. A class, on the other hand, represents just a blueprint from which we’ll create objects. Within a class, we define the characteristics and behavior that objects will have.
Objects are created from classes and represent a physical entity. Once created, they exist in memory until we no longer need them. Each object that is no longer used in our application will become eligible for garbage collection. In other words, Java will remove unused objects from memory so our program will have enough memory to continue with its execution.
Let’s create a Student class:
public class Student { private String name; private String code; private int age; public Student(String name, String code, int age){ this.name = name; this.code = code; this.age = age; } // getters and setters }
Following, let’s create an object using the Student class:
new Student("Anna", "438630", 17);
Every object is created using the new keyword followed by the constructor. However, an exception to this rule is creating objects from the String class.
Furthermore, we can create a String object by directly assigning a value:
"Test"
Reference in Java
In the code snippets from the previous section, we only created the objects; we didn’t assign them to any variable, and without assigning them to a variable, we don’t have any use for them.
A reference is a specific type of variable that allows us to access objects in memory. Unlike some other programming languages, Java doesn’t allow us to access objects in memory directly. Instead, we need to use references to access the object.
Moving forward, let’s assign the Student object to the reference:
Student student = new Student("Anna", "438630", 17);
A reference is nothing more than the type of a variable that points to an object in memory.
With reference, we can access the object’s characteristic:
System.out.println(student.getName()) // prints Anna
Differences Between Object And Reference
To summarize, let’s list the differences between objects and references in the table view:
Object | Reference |
Lives on the heap and doesn’t have a name. | Has a name. |
We can’t access the object. | Used to access the content of an object. |
Different shapes and sizes. Each object takes a different amount of memory. | All references are the same size regardless of the type. |
Garbage collectible. | Not garbage collectible. |
Conclusion
In this quick article, we learned the differences between objects and references in Java.