Comparing Objects
Comparing Objects
What are Objects?
- Objects are instances of classes.
- Each object has its own state (data) and methods (functions) that work with the state.
- In Java, when two objects are created, they are stored in separate memory locations.
Comparison Operators for Objects
- Most comparison operators, such as
==and!=, can be used with objects. - But they do not compare the values of the objects.
- Instead, they compare whether the variables are pointing to the same object in memory.
Equals Method
- Equals method (
object1.equals(object2)) can be used to compare the values of two objects. - This method can be overridden in a class to specify how two instances of that class should be compared.
CompareTo Method
- CompareTo Method (
object1.compareTo(object2)) compares two objects to see which comes first. - It returns a negative number, zero, or a positive number if
object1is less than, equal to, or greater thanobject2respectively. - This is commonly used for sorting purposes.
NullPointerException
- A NullPointerException can occur when trying to access a method or field of an object that is
null. - This happens because
nullmeans there is no object present. - Always check an object for
nullbefore accessing its methods or fields.
Instanceof Operator
- Instanceof operator (
object1 instanceof Object2) checks if an object is an instance of a certain class. - It returns a boolean value -
Trueifobject1is an instance ofObject2class.
getClass and getName Methods
- ` getClass()
method from theObject` class returns the class of an object. getName()method from theClassclass returns the name of the class as a String.- Together,
object.getClass().getName()will return the class name of an object as a String.