Comparing Objects
Explore how to compare Java objects by creating custom equals methods and using the == operator correctly. Understand when to compare references versus object content, and how to avoid runtime errors like NullPointerException. This lesson covers comparing complex objects and designing equality checks for custom classes to enhance your coding skills.
We'll cover the following...
Introduction
Comparing objects is a little different than comparing primitive type values, like numbers. Objects can be very complex and can have many attribute values or instance variables inside them.
Suppose we have a Person object. It includes the variables: name, address, phone, and age. To compare two Person objects, we can’t simply use the == or != operator. We have to design an equal method that compares the objects because comparing the objects means comparing their instance variables and values.
Using == and != operator
In Unit 2, we talked about the difference between the == and equals method when comparing strings. With String and other objects, we almost ...