{"id":617,"date":"2017-05-01T11:37:07","date_gmt":"2017-05-01T03:37:07","guid":{"rendered":"https:\/\/www.techcoil.com\/blog\/?p=617"},"modified":"2018-09-05T00:21:33","modified_gmt":"2018-09-04T16:21:33","slug":"things-object-class-java-programmers-know","status":"publish","type":"post","link":"https:\/\/www.techcoil.com\/blog\/things-object-class-java-programmers-know\/","title":{"rendered":"Things about the Object class in Java that programmers ought to know about"},"content":{"rendered":"<p>After <a href=\"https:\/\/www.techcoil.com\/blog\/getting-started-with-java-programming\/\" target=\"_blank\">getting started with Java development<\/a>, getting to know the <a href=\"https:\/\/docs.oracle.com\/javase\/7\/docs\/api\/java\/lang\/Object.html\" target=\"_blank\"><code>Object<\/code><\/a> class well is one of the next steps that programmers should undertake to be proficient with the Java programming language. This post lists some points about the <code>Object<\/code> class in Java that programmers ought to know about in order to code well in the Java programming language.<\/p>\n<h2>Every class that we define will extend from the Object class; directly or indirectly<\/h2>\n<p>Like it or not, the <code>Object<\/code> class will be the superclass of all classes. Going by the rule of inheritance, this will mean that every class that we define in Java will inherit the following methods:<\/p>\n<ul>\n<li><a href=\"https:\/\/docs.oracle.com\/javase\/7\/docs\/api\/java\/lang\/Object.html#getClass()\" target=\"_blank\"><code>getClass()<\/code><\/a><\/li>\n<li><code><a href=\"https:\/\/docs.oracle.com\/javase\/7\/docs\/api\/java\/lang\/Object.html#equals(java.lang.Object)\" target=\"_blank\">equals()<\/a><\/code><\/li>\n<li><code><a href=\"https:\/\/docs.oracle.com\/javase\/7\/docs\/api\/java\/lang\/Object.html#hashCode()\" target=\"_blank\">hashCode()<\/a><\/code><\/li>\n<li><a href=\"https:\/\/docs.oracle.com\/javase\/7\/docs\/api\/java\/lang\/Object.html#toString()\" target=\"_blank\"><code>toString()<\/code><\/a><\/li>\n<li><code><a href=\"https:\/\/docs.oracle.com\/javase\/7\/docs\/api\/java\/lang\/Object.html#clone()\">clone()<\/a><\/code><\/li>\n<li>3 different signatures of wait; <a href=\"https:\/\/docs.oracle.com\/javase\/7\/docs\/api\/java\/lang\/Object.html#wait()\" target=\"_blank\"><code>wait()<\/code><\/a>, <a href=\"https:\/\/docs.oracle.com\/javase\/7\/docs\/api\/java\/lang\/Object.html#wait(long)\" target=\"_blank\"><code>wait(long timeout)<\/code><\/a> and <a href=\"https:\/\/docs.oracle.com\/javase\/7\/docs\/api\/java\/lang\/Object.html#wait(long,%20int)\" target=\"_blank\"><code>wait(long timeout, int nanos)<\/code><\/a><\/li>\n<li><a href=\"https:\/\/docs.oracle.com\/javase\/7\/docs\/api\/java\/lang\/Object.html#notify()\" target=\"_blank\"><code>notify()<\/code><\/a><\/li>\n<li><a href=\"https:\/\/docs.oracle.com\/javase\/7\/docs\/api\/java\/lang\/Object.html#notifyAll()\" target=\"_blank\"><code>notifyall()<\/code><\/a><\/li>\n<li><code><a href=\"https:\/\/docs.oracle.com\/javase\/7\/docs\/api\/java\/lang\/Object.html#finalize()\" target=\"_blank\">finalize()<\/a><\/code><\/li>\n<\/ul>\n<h3>Understanding the getClass() method of the Object class<\/h3>\n<p>The <code>getClass()<\/code> method returns a <a href=\"https:\/\/docs.oracle.com\/javase\/7\/docs\/api\/java\/lang\/Class.html\" target=\"_blank\">Class<\/a> object that describes the class that we define. Through the <code>getClass()<\/code> method, we will be able to use the facilities of Java reflection to:<\/p>\n<ul>\n<li>Dynamically create instances of the Class of the object that we had called <code>getClass()<\/code> on.<\/li>\n<li>Dynamically execute the methods of the object that we had called <code>getClass()<\/code> on.<\/li>\n<li>Discover annotations defined in the Class of the object that we had called <code>getClass()<\/code> on.<\/li>\n<li>Discover the methods and variables in the Class of the object that we had called <code>getClass()<\/code> on.<\/li>\n<\/ul>\n<p>Developers do not override the <code>getClass()<\/code> method in practice.  <\/p>\n<h3>Understanding the equals() method of the Object class<\/h3>\n<p>If you look into the method definition of the <code>equals()<\/code> method defined in the Object class, you will observe that the <code>equals()<\/code> method in the <code>Object<\/code> class merely returned the boolean comparison of its input parameter with itself:<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\n    public boolean equals(Object obj) {\r\n        return (this == obj);\r\n    }\r\n<\/pre>\n<p>This is known as reference comparison. Hence, if you do not override the <code>equals()<\/code> method of the <code>Object<\/code> class, the <code>equals()<\/code> method of your class will only return true when you pass the same object as the input parameter to the <code>equals()<\/code> method of the object that you had invoked. <\/p>\n<p>With the original implementation of the <code>equals()<\/code> method in the <code>Object<\/code> class, the following code will return true:<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\npublic class Person {\r\n\t\r\n\tprivate String name;\r\n\tprivate int age;\r\n\t\r\n\tpublic Person(String name, int age) {\r\n\t\tthis.name = name;\r\n\t\tthis.age = age;\r\n\t}\r\n\t\r\n\tpublic static void main(String&#x5B;] args) {\r\n\t\tPerson john = new Person(&quot;John&quot;, 21);\r\n\t\tSystem.out.println(john.equals(john));\r\n\t}\r\n\r\n}\r\n<\/pre>\n<p>and the following code will return false, even though we expect the two <code>Person<\/code> objects to be equal since they have the same name and age:<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\npublic class Person {\r\n\t\r\n\tprivate String name;\r\n\tprivate int age;\r\n\t\r\n\tpublic Person(String name, int age) {\r\n\t\tthis.name = name;\r\n\t\tthis.age = age;\r\n\t}\r\n\r\n\tpublic static void main(String&#x5B;] args) {\r\n\t\tPerson john1 = new Person(&quot;John&quot;, 21);\r\n\t\tPerson john2 = new Person(&quot;John&quot;, 21);\r\n\t\tSystem.out.println(john1.equals(john2));\r\n\t}\r\n\t\r\n}\r\n<\/pre>\n<h4>When should we override the equals() method of the Object class?<\/h4>\n<p>In practice, if we expect that instances of the class that we define to be compared for equality, we should override the <code>equals()<\/code> method to reflect what we intend for <strong>two separate instances<\/strong> of our class <strong>to be equal<\/strong>.<\/p>\n<h4>How would we override the equals() method of the Object class?<\/h4>\n<p>Typically the logic to override the equals() method is as follows:<\/p>\n<ol>\n<li>Check whether the Object in the input parameter is of the same Class type as the instance that the equals() method is invoked on.<\/li>\n<li>If the input parameter is of the same Class type, check each instance field of both instances to see if they are the same. If all the instance fields of both instances are the same, return true.<\/li>\n<li>Returns false for all other cases.<\/li>\n<\/ol>\n<p>An example implementation of the <code>equals()<\/code> method for the Person class would be as follows:<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\n\t@Override\r\n\tpublic boolean equals(Object another) {\r\n\t\t\r\n\t\tif (another instanceof Person) {\r\n\t\t\tPerson anotherPerson = (Person) another;\r\n\t\t\treturn this.name.equals(anotherPerson.name) &amp;&amp; this.age == anotherPerson.age;\r\n\t\t}\r\n\t\t\r\n\t\treturn false;\r\n\t}\r\n<\/pre>\n<h3>Understanding the hashCode() method of the Object class<\/h3>\n<p>The <code>hashCode()<\/code> method is meant to return an integer representation of the instance which the <code>hashCode()<\/code> method is invoked on. By default, the <code>hashCode()<\/code> method of the <code>Object<\/code> class returns the integer representation of the identifier of the instance which the <code>hashCode()<\/code> method is invoked on. We can observe this characteristic with the following code:<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\npublic class Person {\r\n\t\r\n\tprivate String name;\r\n\tprivate int age;\r\n\t\r\n\tpublic Person(String name, int age) {\r\n\t\tthis.name = name;\r\n\t\tthis.age = age;\r\n\t}\r\n\r\n\tpublic static void main(String&#x5B;] args) {\r\n\t\tPerson john1 = new Person(&quot;John&quot;);\r\n\t\tPerson john2 = new Person(&quot;John&quot;);\r\n\t\tPerson john3 = john1;\r\n\t\tSystem.out.println(&quot;John 1's hashCode: &quot; + john1.hashCode());\r\n\t\tSystem.out.println(&quot;John 2's hashCode: &quot; + john2.hashCode());\r\n\t\tSystem.out.println(&quot;John 3's hashCode: &quot; + john3.hashCode());\r\n\t}\r\n\t\r\n}\r\n<\/pre>\n<p>Running the above codes gave me the following output in my console terminal:<\/p>\n<pre class=\"brush: bash; title: ; notranslate\" title=\"\">\r\nJohn 1's hashCode: 167772895\r\nJohn 2's hashCode: 113017754\r\nJohn 3's hashCode: 167772895\r\n<\/pre>\n<p>Since <code>john1<\/code> and <code>john3<\/code> variables referenced the same Person instance, the hash codes are the same. Also note that since the identifier of object instances are generated randomly, different runs of the code will result in different hash codes being printed.<\/p>\n<h4>When should we override the hashCode() method of the Object class<\/h4>\n<p>In practice, if we override the <code>equals()<\/code> method, we should also override the <code>hashCode()<\/code> method. If two objects are deemed to be equal by the overridden <code>equals()<\/code> method, the integer value returned from their <code>hashCode()<\/code> method should also be the same. However, note that two objects can return the same hash code values via their <code>hashCode()<\/code> method even though they are not equal. <\/p>\n<h4>How would we override the hashCode() method of the Object class<\/h4>\n<p>A good implementation of the <code>hashCode()<\/code> method will be one that will result in a proper distribution of hash values for different instances of the class that we define. One good implementation suggested by <a href=\"http:\/\/amzn.to\/2pjb6Bq\" target=\"_blank\">Joshua Bloch's Effective Java<\/a> is as follows:<\/p>\n<ol>\n<li>Create a int result and assign a non-zero value.<\/li>\n<li>For every field f tested in the equals() method, calculate a hash code <code>c<\/code> with the following guidelines:\n<ul>\n<li>If the field f is a boolean: calculate (f ? 0 : 1);<\/li>\n<li>If the field f is a byte, char, short or int: calculate (int)f;<\/li>\n<li>If the field f is a long: calculate (int)(f ^ (f >>> 32));<\/li>\n<li>If the field f is a float: calculate Float.floatToIntBits(f);<\/li>\n<li>If the field f is a double: calculate Double.doubleToLongBits(f) and handle the return value like every long value;<\/li>\n<li>If the field f is an object: Use the result of the hashCode() method or 0 if f == null;<\/li>\n<li>If the field f is an array: see every field as separate element and calculate the hash value in a recursive fashion and combine the values as described next.<\/li>\n<\/ul>\n<\/li>\n<li>Combine the hash value c with result:<br \/>\nresult = 37 * result + c<\/li>\n<li>Return result.<\/li>\n<\/ol>\n<p>Going by this set of guidelines, an example implementation of the <code>hashCode()<\/code> method for the Person class would be as follows:<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\n\t@Override\r\n\tpublic int hashCode() {\r\n\t\t\r\n\t    int result = 0;\r\n\t \r\n\t    \/\/ If the field f is an object: Use the result of the hashCode() method or 0 if f == null;\r\n\t    if (this.name != null) {\r\n\t        \/\/ 37 * 0 is 0, so we can reduce to this assignment\r\n\t        result = this.name.hashCode();\r\n\t    }\r\n\t \r\n\t    \/\/ If the field f is a byte, char, short or int: calculate (int)f;\r\n\t    result = 37 * result + this.age;\r\n\t     \r\n\t    return result;\r\n\t \r\n\t}\r\n<\/pre>\n<h3>Understanding the toString() method of the Object class<\/h3>\n<p>While the <code>hashCode()<\/code> method is for generating a integer representation of the instance of your class, the <code>toString()<\/code> method is meant for generating a <a href=\"https:\/\/docs.oracle.com\/javase\/7\/docs\/api\/java\/lang\/String.html\" target=\"_blank\">String<\/a> representation of the instance of your class. The <code>toString()<\/code> method that is implemented by the <code>Object<\/code> class is as follows:<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\n    public String toString() {\r\n        return getClass().getName() + &quot;@&quot; + Integer.toHexString(hashCode());\r\n    }\r\n<\/pre>\n<p>Hence, if we do not override the <code>toString()<\/code> method in our class, the default String representation of the instance of our class will be the name of our class, followed by an '@' character and then the hexadecimal value of what our <code>hashCode()<\/code> returns. If we run the following code:<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\npublic class Person {\r\n\r\n    private String name;\r\n    private int age;\r\n\r\n    public Person(String name, int age) {\r\n        this.name = name;\r\n        this.age = age;\r\n    }\r\n\r\n    @Override\r\n    public boolean equals(Object another) {\r\n\r\n        if (another instanceof Person) {\r\n            Person anotherPerson = (Person) another;\r\n            return this.name.equals(anotherPerson.name) &amp;&amp; this.age == anotherPerson.age;\r\n        }\r\n\r\n        return false;\r\n    }\r\n\r\n    @Override\r\n    public int hashCode() {\r\n\r\n        int result = 0;\r\n\r\n        \/\/ If the field f is an object: Use the result of the hashCode() method or 0 if f == null;\r\n        if (this.name != null) {\r\n            \/\/ 37 * 0 is 0, so we can reduce to this assignment\r\n            result = this.name.hashCode();\r\n        }\r\n\r\n        \/\/ If the field f is a byte, char, short or int: calculate (int)f;\r\n        result = 37 * result + this.age;\r\n\r\n        return result;\r\n\r\n    }\r\n\r\n    public static void main(String&#x5B;] args) {\r\n        Person john1 = new Person(&quot;John&quot;, 21);\r\n        System.out.println(john1.toString());\r\n    }\r\n\r\n}\r\n<\/pre>\n<p>The output would be as follows:<\/p>\n<pre class=\"brush: bash; title: ; notranslate\" title=\"\">\r\nPerson@51abb4c\r\n<\/pre>\n<h4>When would we override the toString() method of the Object class<\/h4>\n<p>Typically, we would override the <code>toString()<\/code> method of the Object class when the class that we are defining is meant for creating value objects, such as an instance of the <code>Person<\/code> class. The overridden <code>toString()<\/code> method of the subclass is usually invoked for logging and debugging purposes. <\/p>\n<h4>How would we override the toString() method of the Object class<\/h4>\n<p>We would typically override the <code>toString()<\/code> method with a String concatenation of private fields that are defined in our subclass as the return value. Most Integrated Development Environment provide a feature that generate a <code>toString()<\/code> method implementation for us. For example in Eclipse Mars, I can trigger the <code>toString()<\/code> method generation by clicking on \"Source\" -> \"Generate toString...\". Doing so with my <code>Person<\/code> class gave me the following wizard:<\/p>\n<p><img decoding=\"async\" src=\"https:\/\/www.techcoil.com\/blog\/wp-content\/uploads\/toString-generation-wizard-in-Eclipse-for-Person-class.jpg\" alt=\"toString() generation wizard in Eclipse for Person class\" \/><\/p>\n<p>Clicking the \"Ok\" button gave me a <code>toString()<\/code> method after my <code>hashCode()<\/code> method implementation:<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\n\t@Override\r\n\tpublic String toString() {\r\n\t\treturn &quot;Person &#x5B;name=&quot; + name + &quot;, age=&quot; + age + &quot;]&quot;;\r\n\t}\r\n<\/pre>\n<h3>Understanding the clone() method of the Object class<\/h3>\n<p>The <code>clone()<\/code> method is a facility that allows subclasses to clone a copy of the instance where the <code>clone()<\/code> method is invoked on. By default, the <code>clone()<\/code> method throws a <a href=\"https:\/\/docs.oracle.com\/javase\/7\/docs\/api\/java\/lang\/CloneNotSupportedException.html\" target=\"_blank\"><code>CloneNotSupportedException<\/code><\/a> when the subclass does not implement the <a href=\"https:\/\/docs.oracle.com\/javase\/7\/docs\/api\/java\/lang\/Cloneable.html\" target=\"_blank\"><code>Cloneable<\/code><\/a> interface. The <code>clone()<\/code> method in the <code>Object<\/code> class returns a field-by-field copy of the object. If your class definition contains custom class types as fields, the field-by-field copying performed by the clone() method of the Object class will not give a true clone of the instance that the <code>clone()<\/code> method is invoked on, as only the references of object instance fields are copied over to the cloned object.   <\/p>\n<h4>When would we override the clone() method of the Object class?<\/h4>\n<p>Typically, we would override the clone() method of the Object class when:<\/p>\n<ol>\n<li>our class A is used as a field within another class B,<\/li>\n<li>and that field in class B can be returned by a method call,<\/li>\n<li>and we do not want any accidental edits made to that instance of class A from outside of class B.<\/li>\n<\/ol>\n<p>By overriding the <code>clone()<\/code> method of the Object class, we are giving the users of our class the ability to clone a copy of an instance via a single method call. If we do not override the <code>clone()<\/code> method of the Object class, users of our class will have to use reflection to get a clone of our class instance when there are fields within our classes that are not accessible from outside our class.  <\/p>\n<h4>How would we override the clone() method of the Object class?<\/h4>\n<p>Taking the example from <a href=\"http:\/\/amzn.to\/2pjb6Bq\" target=\"_blank\">Joshua Bloch's Effective Java<\/a>, we would override the <code>clone()<\/code> method in the <code>Person<\/code> class to be as follows:<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\n\t@Override\r\n\tpublic Person clone() {\r\n\t\ttry {\r\n\t\t\treturn (Person) super.clone();\r\n\t\t} catch (CloneNotSupportedException e) {\r\n\t\t\tthrow new AssertionError(); \/\/ can never happen\r\n\t\t}\r\n\t}\r\n<\/pre>\n<p>This implementation would suffice as the age field is a primitive data type and the name field is a String, which is an immutable class. However, if there is a field of a custom class, we will have to clone the field and set it to the instance returned from the clone() method from the Object class. To visualize this, suppose that we have an <code>Address<\/code> class with the following class definition:<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\npublic class Address implements Cloneable {\r\n\t\r\n\tprivate String street;\r\n\r\n\tpublic Address(String street) {\r\n\t\tthis.street = street;\r\n\t}\r\n\t\r\n\t@Override\r\n\tpublic boolean equals(Object another) {\r\n\t\t\r\n\t\tif(another instanceof Address) {\r\n\t\t\tAddress anotherAddress = (Address)another;\r\n\t\t\treturn anotherAddress.street.equals(this.street);\r\n\t\t}\r\n\t\t\r\n\t\treturn false;\r\n\t\t\r\n\t}\r\n\t\r\n\t@Override \r\n\tpublic int hashCode() {\r\n\t\treturn street.hashCode();\r\n\t}\r\n\t\r\n\t@Override \r\n\tpublic Address clone() {\r\n\t\t\r\n\t\ttry {\r\n\t\t\treturn (Address) super.clone();\r\n\t\t} catch (CloneNotSupportedException e) {\r\n\t\t\tthrow new AssertionError(); \/\/ can never happen\r\n\t\t}\r\n\t\t\r\n\t}\r\n\t\r\n}\r\n<\/pre>\n<p>And suppose that the <code>Person<\/code> class has a new field of type address, the implementation of the <code>clone()<\/code> method will become:<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\n\t@Override\r\n\tpublic Person clone() {\r\n\t\ttry {\r\n\t\t\tPerson person = (Person) super.clone();\r\n\t\t\tperson.setAddress(this.address.clone());\r\n\t\t\treturn person;\r\n\t\t} catch (CloneNotSupportedException e) {\r\n\t\t\tthrow new AssertionError(); \/\/ can never happen\r\n\t\t}\r\n\t}\r\n<\/pre>\n<p>Note that the <code>clone()<\/code> method is possible in the <code>Person<\/code> class because the <code>Address<\/code> class has overridden the <code>clone()<\/code> method as well. <\/p>\n<h3>Understanding the the wait(), notify() and notifyAll() methods of the Object class<\/h3>\n<p>Every Object instance can be used as a monitor that coordinates thread execution within a code segment. When an object instance is wrapped around a synchronized block, there can only be one <a href=\"https:\/\/docs.oracle.com\/javase\/7\/docs\/api\/java\/lang\/Thread.html\" target=\"_blank\">Thread<\/a> running the synchronized code block. The <code>wait()<\/code>, <code>notify()<\/code> and <code>notifyAll()<\/code> methods are thread synchronization mechanism and can only be called:<\/p>\n<ul>\n<li>when an object is wrapped in a synchronized block like this:\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\n\t\tsynchronized(anObjectInstance) {\r\n\t\t\t\/\/ Code region that can only be accessed by the Thread that owns anObjectInstance's monitor \r\n\t\t}\r\n<\/pre>\n<\/li>\n<li>and by the Thread that owns the object's monitor. A Thread that owns the object's monitor is the <strong>only one<\/strong> at any point in time that managed to enter one of the synchronized blocks that had wrapped around an object instance.<\/li>\n<\/ul>\n<h4>Function of the wait() methods<\/h4>\n<p>The <code>wait()<\/code> methods allow a thread that owns the object's monitor to give up the ownership so that other threads can have a chance to enter one of the synchronized blocks that had wrapped around that object instance. Typically, we would use one of the <code>wait()<\/code> methods if the thread that owns the object's monitor requires some condition to be fulfilled in order to proceed further. Calling the <code>wait()<\/code> method will give some other Thread the chance to own the object's monitor; in the hope that the next running Thread will get to fulfill the condition that the current Thread needs for proceeding. After the Thread invokes a <code>wait()<\/code> method, it will wait until another Thread invokes either the <code>notify()<\/code> or <code>notifyAll()<\/code> method. If some positive numeric parameters are passed into the <code>wait()<\/code> method, the Thread will be awaken if no calls are made to either <code>notify()<\/code> or <code>notifyAll()<\/code> within a time duration that are indicated by the numeric parameters.<\/p>\n<h4>Function of the notify() and notifyAll() methods<\/h4>\n<p>The <code>notify()<\/code> method triggers a notification to a Thread that is waiting for a notification while the <code>notifyAll()<\/code> method triggers a notification to <strong>all<\/strong> the Threads that are waiting for a notification. The recipients of the notification can then proceed on with running codes that come after the <code>wait()<\/code> method that caused them to wait.<\/p>\n<h3>Understanding the finalize() method of the Object class<\/h3>\n<p>The <code>finalize()<\/code> method of the <code>Object<\/code> class is meant for the garbage collector to call so that the instance which the <code>finalize()<\/code> method is invoked on has chances to release any resources that it holds. Since there is no guarantee that the <code>finalize()<\/code> method will be called promptly or even called at all, Joshua Blotch had recommended Java developers to avoid implementing the <code>finalize()<\/code> method. Instead of relying on the finalize() method to release resources held by instances of our class, we should provide explicit methods for users of our class to release those resources when the instance of our class is no longer needed. <\/p>\n<h2>The toString() method is called implicitly when concatenating Strings with instances<\/h2>\n<p>When we \"add\" Object instances to Strings, the <code>toString()<\/code> methods of the object instances will be called implicitly. For example, with the following code:<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\npublic class Person {\r\n\r\n    private String name;\r\n    private int age;\r\n\r\n    public Person(String name, int age) {\r\n        this.name = name;\r\n        this.age = age;\r\n    }\r\n    \r\n    @Override\r\n    public String toString() {\r\n        return &quot;Person &#x5B;name=&quot; + name + &quot;, age=&quot; + age + &quot;]&quot;;\r\n    }\r\n    \r\n    public static void main(String&#x5B;] args) {\r\n\r\n        Person john = new Person(&quot;John&quot;, 22);\r\n        Person susan = new Person(&quot;Susan&quot;, 23);\r\n\t\t\r\n        System.out.println(&quot;john contains: &quot; + john + &quot; susan contains: &quot; + susan);\r\n    } \r\n\r\n}\r\n<\/pre>\n<p>We will get the following output:<\/p>\n<pre class=\"brush: bash; title: ; notranslate\" title=\"\">\r\njohn contains: Person &#x5B;name=John, age=22] susan contains: Person &#x5B;name=Susan, age=23]\r\n<\/pre>\n<h2>The equals() and hashCode() methods are used when an object instance is added to and removed from a HashSet<\/h2>\n<p>When we add an object instance to a <a href=\"https:\/\/docs.oracle.com\/javase\/7\/docs\/api\/java\/util\/HashSet.html\" target=\"_blank\"><code>HashSet<\/code><\/a>, the <code>equals()<\/code> and <code>hashCode()<\/code> methods are utilized to determine whether the object instance is a duplicate to the existing items in the <code>HashSet<\/code>. We can see how the <code>equals()<\/code> and <code>hashCode()<\/code> methods are utilized when an object instance is added to and removed from a <code>HashSet<\/code> by running the following code: <\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\nimport java.util.HashSet;\r\n\r\npublic class Person {\r\n     \r\n    private String name;\r\n    private int age;\r\n     \r\n    public Person(String name, int age) {\r\n        this.name = name;\r\n        this.age = age;\r\n    }\r\n \r\n    @Override\r\n    public boolean equals(Object another) {\r\n         \r\n        System.out.println(&quot;equals() is called to test whether (&quot; + this + &quot;) equals (&quot; + another + &quot;).&quot;);\r\n         \r\n        if (another instanceof Person) {\r\n            Person anotherPerson = (Person) another;\r\n            return this.name.equals(anotherPerson.name) &amp;&amp; this.age == anotherPerson.age;\r\n        } \r\n         \r\n         \r\n        return false;\r\n    }\r\n \r\n    @Override\r\n    public int hashCode() {\r\n         \r\n    \tSystem.out.println(&quot;hashCode() is called for (&quot; + this + &quot;).&quot;); \r\n         \r\n        int result = 0;\r\n      \r\n        \/\/ If the field f is an object: Use the result of the hashCode() method or 0 if f == null;\r\n        if (this.name != null) {\r\n            \/\/ 37 * 0 is 0, so we can reduce to this assignment\r\n            result = this.name.hashCode();\r\n        }\r\n      \r\n        \/\/ If the field f is a byte, char, short or int: calculate (int)f;\r\n        result = 37 * result + this.age;\r\n          \r\n        return result;\r\n      \r\n    }\r\n     \r\n    @Override\r\n    public String toString() {\r\n        return &quot;Person &#x5B;name=&quot; + name + &quot;, age=&quot; + age + &quot;]&quot;;\r\n    }\r\n \r\n    public static void main(String&#x5B;] args) {\r\n \r\n        HashSet&lt;Person&gt; personHashSet = new HashSet&lt;Person&gt;();\r\n        \r\n        System.out.println(&quot;Adding John to hash set.&quot;);\r\n        personHashSet.add(new Person(&quot;John&quot;, 22));\r\n\r\n        System.out.println(&quot;Adding Susan to hash set.&quot;);\r\n        personHashSet.add(new Person(&quot;Susan&quot;, 23));\r\n\r\n        System.out.println(&quot;Adding John to hash set again.&quot;);\r\n        personHashSet.add(new Person(&quot;John&quot;, 22));\r\n\r\n        System.out.println();\r\n        System.out.println(&quot;Contents in personHashSet:&quot;); \r\n        System.out.println(personHashSet);\r\n        System.out.println();\r\n\r\n        personHashSet.remove(new Person(&quot;John&quot;, 22));\r\n\r\n        System.out.println();\r\n        System.out.println(&quot;Contents in personHashSet after removal:&quot;); \r\n        System.out.println(personHashSet);\r\n\r\n    }\r\n}\r\n<\/pre>\n<p>Running the above code will give us the following output:<\/p>\n<pre class=\"brush: bash; title: ; notranslate\" title=\"\">\r\nAdding John to hash set.\r\nhashCode() is called for (Person &#x5B;name=John, age=22]).\r\nAdding Susan to hash set.\r\nhashCode() is called for (Person &#x5B;name=Susan, age=23]).\r\nAdding John to hash set again.\r\nhashCode() is called for (Person &#x5B;name=John, age=22]).\r\nequals() is called to test whether (Person &#x5B;name=John, age=22]) equals (Person &#x5B;name=John, age=22]).\r\n\r\nContents in personHashSet:\r\n&#x5B;Person &#x5B;name=Susan, age=23], Person &#x5B;name=John, age=22]]\r\nhashCode() is called for (Person &#x5B;name=John, age=22]).\r\nequals() is called to test whether (Person &#x5B;name=John, age=22]) equals (Person &#x5B;name=John, age=22]).\r\n\r\nContents in personHashSet after removal:\r\n&#x5B;Person &#x5B;name=Susan, age=23]]\r\n<\/pre>\n<p>From the output, we can observe that the first two invocation of the <code>add<\/code> method on <code>personHashSet<\/code> had resulted in only the <code>hashCode()<\/code> method of the Person instance to be called. However, at the third invocation of the <code>add()<\/code> method on <code>personHashSet<\/code>, the <code>equals()<\/code> method of the <code>Person<\/code> instance was called after the call to its <code>hashCode()<\/code> method.<\/p>\n<p>Since the <code>equals()<\/code> method on the third invocation of the <code>add()<\/code> method on <code>personHashSet<\/code> would have evaluated to true, we only saw two records when we print <code>personHashSet<\/code> after the invocations of the <code>add()<\/code> method on <code>personHashSet<\/code>.<\/p>\n<p>When we removed the record for John in <code>personHashSet<\/code> via an invocation of the <code>remove()<\/code> method on <code>personHashSet<\/code>, we see that the <code>hashCode()<\/code> method and the <code>equals()<\/code> method of the <code>Person<\/code> instance was called again in the same sequence as the third invocation of the <code>add()<\/code> method on <code>personHashSet<\/code>. <\/p>\n<h2>The equals() and hashCode() methods are used when an object instance is used as a key in a HashMap<\/h2>\n<p>When we use an object instance as a key in a <a href=\"https:\/\/docs.oracle.com\/javase\/7\/docs\/api\/java\/util\/HashMap.html\" target=\"_blank\"><code>HashMap<\/code><\/a>, the <code>equals()<\/code> and <code>hashCode()<\/code> methods will be used for certain operations of the <code>HashMap<\/code>. To see how the <code>equals()<\/code> and <code>hashCode()<\/code> methods of an object instance are used in a HashMap, we can run the following code:<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\nimport java.util.HashMap;\r\n\r\npublic class Person {\r\n     \r\n    private String name;\r\n    private int age;\r\n     \r\n    public Person(String name, int age) {\r\n        this.name = name;\r\n        this.age = age;\r\n    }\r\n \r\n    @Override\r\n    public boolean equals(Object another) {\r\n         \r\n        System.out.println(&quot;equals() is called to test whether (&quot; + this + &quot;) equals (&quot; + another + &quot;).&quot;);\r\n         \r\n        if (another instanceof Person) {\r\n            Person anotherPerson = (Person) another;\r\n            return this.name.equals(anotherPerson.name) &amp;&amp; this.age == anotherPerson.age;\r\n        } \r\n         \r\n         \r\n        return false;\r\n    }\r\n \r\n    @Override\r\n    public int hashCode() {\r\n         \r\n    \tSystem.out.println(&quot;hashCode() is called for (&quot; + this + &quot;).&quot;); \r\n         \r\n        int result = 0;\r\n      \r\n        \/\/ If the field f is an object: Use the result of the hashCode() method or 0 if f == null;\r\n        if (this.name != null) {\r\n            \/\/ 37 * 0 is 0, so we can reduce to this assignment\r\n            result = this.name.hashCode();\r\n        }\r\n      \r\n        \/\/ If the field f is a byte, char, short or int: calculate (int)f;\r\n        result = 37 * result + this.age;\r\n          \r\n        return result;\r\n      \r\n    }\r\n     \r\n    @Override\r\n    public String toString() {\r\n        return &quot;Person &#x5B;name=&quot; + name + &quot;, age=&quot; + age + &quot;]&quot;;\r\n    }\r\n \r\n    public static void main(String&#x5B;] args) {\r\n \r\n        HashMap&lt;Person, String&gt; personHashMap = new HashMap&lt;Person, String&gt;();\r\n        \r\n        System.out.println(&quot;Putting John inside personHashMap&quot;);\r\n        Person john = new Person(&quot;John&quot;, 22);\r\n        personHashMap.put(john, &quot;a man&quot;);\r\n        \r\n        System.out.println(&quot;Putting Susan inside personHashMap&quot;);\r\n        Person susan = new Person(&quot;Susan&quot;, 23);\r\n        personHashMap.put(susan, &quot;a woman&quot;);\r\n        \r\n        System.out.println(&quot;Putting John inside personHashMap again&quot;);\r\n        personHashMap.put(new Person(&quot;John&quot;, 22), &quot;is the same man&quot;);\r\n        \r\n        System.out.println();\r\n        System.out.println(&quot;Contents in personHashMap&quot;);\r\n        System.out.println(personHashMap);\r\n        System.out.println();\r\n\r\n        System.out.println(&quot;Getting the value indexed by John&quot;);\r\n        System.out.println(&quot;John is &quot; + personHashMap.get(new Person(&quot;John&quot;, 22)));\r\n        \r\n        System.out.println();\r\n        System.out.println(&quot;Removing John from personHashMap&quot;);\r\n        personHashMap.remove(new Person(&quot;John&quot;, 22));\r\n        \r\n        System.out.println();\r\n        System.out.println(&quot;Contents in personHashMap&quot;);\r\n        System.out.println(personHashMap);\r\n        System.out.println();\r\n        \r\n    }\r\n}\r\n<\/pre>\n<p>Running the above code will give us the following output: <\/p>\n<pre class=\"brush: bash; title: ; notranslate\" title=\"\">\r\nPutting John inside personHashMap\r\nhashCode() is called for (Person &#x5B;name=John, age=22]).\r\nPutting Susan inside personHashMap\r\nhashCode() is called for (Person &#x5B;name=Susan, age=23]).\r\nPutting John inside personHashMap again\r\nhashCode() is called for (Person &#x5B;name=John, age=22]).\r\nequals() is called to test whether (Person &#x5B;name=John, age=22]) equals (Person &#x5B;name=John, age=22]).\r\n\r\nContents in personHashMap\r\n{Person &#x5B;name=Susan, age=23]=a woman, Person &#x5B;name=John, age=22]=is the same man}\r\n\r\nGetting the value indexed by John\r\nhashCode() is called for (Person &#x5B;name=John, age=22]).\r\nequals() is called to test whether (Person &#x5B;name=John, age=22]) equals (Person &#x5B;name=John, age=22]).\r\nJohn is is the same man\r\n\r\nRemoving John from personHashMap\r\nhashCode() is called for (Person &#x5B;name=John, age=22]).\r\nequals() is called to test whether (Person &#x5B;name=John, age=22]) equals (Person &#x5B;name=John, age=22]).\r\n\r\nContents in personHashMap\r\n{Person &#x5B;name=Susan, age=23]=a woman}\r\n<\/pre>\n<p>From the output, we can observe that the first two invocations of the <code>put()<\/code> method on <code>personHashMap<\/code> had resulted in only the <code>hashCode()<\/code> method of the Person instance to be called. However, when it comes to putting in a new <code>Person<\/code> instance with a duplicated as a key, the <code>equals()<\/code> method of the <code>Person<\/code> instance was called after a call to the <code>hashCode()<\/code> method. When we print out the contents of <code>personHashMap<\/code>, we can see that the duplicated record had taken over the first record that we had put into <code>personHashMap<\/code> for John.<\/p>\n<p>When we attempted to get the value indexed by John, we can see that both the <code>hashCode()<\/code> and <code>equals()<\/code> method were utilized in the call of the <code>get()<\/code> method on <code>personHashMap<\/code>.<\/p>\n<p>Finally, in the removal of the record for John, we can see that both the <code>hashCode()<\/code> and <code>equals()<\/code> method were utilized in the call of the <code>remove()<\/code> method on <code>personHashMap<\/code>.<\/p>\n\n      <ul id=\"social-sharing-buttons-list\">\n        <li class=\"facebook\">\n          <a href=\"https:\/\/www.facebook.com\/sharer\/sharer.php?u=https%3A%2F%2Fwp.me%2Fp245TQ-9X\" target=\"_blank\" role=\"button\" rel=\"nofollow\">\n            <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/Facebook.png\" alt=\"Facebook icon\"> Share\n          <\/a>\n        <\/li>\n        <li class=\"twitter\">\n          <a href=\"https:\/\/twitter.com\/intent\/tweet?text=&url=https%3A%2F%2Fwp.me%2Fp245TQ-9X&via=Techcoil_com\" target=\"_blank\" role=\"button\" rel=\"nofollow\">\n          <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/Twitter.png\" alt=\"Twitter icon\"> Tweet\n          <\/a>\n        <\/li>\n        <li class=\"linkedin\">\n          <a href=\"https:\/\/www.linkedin.com\/shareArticle?mini=1&title=&url=https%3A%2F%2Fwp.me%2Fp245TQ-9X&source=https:\/\/www.techcoil.com\" target=\"_blank\" role=\"button\" rel=\"nofollow\">\n          <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/linkedin.png\" alt=\"Linkedin icon\"> Share\n          <\/a>\n        <\/li>\n        <li class=\"pinterest\">\n          <a href=\"https:\/\/pinterest.com\/pin\/create\/button\/?url=https%3A%2F%2Fwww.techcoil.com%2Fblog%2Fwp-json%2Fwp%2Fv2%2Fposts%2F617&description=\" class=\"pin-it-button\" target=\"_blank\" role=\"button\" rel=\"nofollow\" count-layout=\"horizontal\">\n          <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/Pinterest.png\" alt=\"Pinterest icon\"> Save\n          <\/a>\n        <\/li>\n      <\/ul>\n    ","protected":false},"excerpt":{"rendered":"<p>After <a href=\"https:\/\/www.techcoil.com\/blog\/getting-started-with-java-programming\/\" target=\"_blank\">getting started with Java development<\/a>, getting to know the <a href=\"https:\/\/docs.oracle.com\/javase\/7\/docs\/api\/java\/lang\/Object.html\" target=\"_blank\"><code>Object<\/code><\/a> class well is one of the next steps that programmers should undertake to be proficient with the Java programming language. This post lists some points about the <code>Object<\/code> class in Java that programmers ought to know about in order to code well in the Java programming language.<\/p>\n","protected":false},"author":1,"featured_media":1220,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"advanced_seo_description":"","jetpack_seo_html_title":"","jetpack_seo_noindex":false,"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"footnotes":""},"categories":[375],"tags":[398,395,402,394,396,6,393,406,408,407,399,400,155,397,401],"jetpack_featured_media_url":"https:\/\/www.techcoil.com\/blog\/wp-content\/uploads\/Java-logo.gif","jetpack_shortlink":"https:\/\/wp.me\/p245TQ-9X","jetpack-related-posts":[],"jetpack_likes_enabled":true,"jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/posts\/617"}],"collection":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/comments?post=617"}],"version-history":[{"count":0,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/posts\/617\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/media\/1220"}],"wp:attachment":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/media?parent=617"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/categories?post=617"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/tags?post=617"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}