5 Java Object class methods interview Q&As

Q1. What are the non-final methods in Java Object class, which are meant primarily for extension?
A1. The non-final methods are

equals( ), hashCode( ), toString( ), clone( ), and finalize( ).

These methods are meant to be overridden. The equals( ) and hashCode( ) methods prove to be very important, when objects implementing these two methods are added to collections. If implemented incorrectly or not implemented at all, then your objects stored in a Map may behave strangely and also it is hard to debug.

The other methods like wait( ), notify( ), notifyAll( ), getClass( ), etc are final methods and therefore cannot be overridden. The methods clone( ) and finalize( ) have protected access.

Q2. Are these methods easy to implement correctly?
A2. No. It is not easy to implement these methods correctly because,

1) You must pay attention to whether your implementation of these methods will continue to work correctly if sub classed. If your class is not meant for extension, then declare your class as final.
2) These methods have to adhere to contracts, and when implementing or overriding a method, the contracts must be satisfied.

Equals() Vs hashCode()

Q3. What are the implications of implementing them incorrectly?
A3. In short, excess debug and rework time. Incorrect implementations of equals( ) and hashCode( ) methods can result in data being lost in HashMaps and Sets. You can also get intermittent data related problems that are harder to consistently reproduce over time.

Here is an example of equals() and hashCode() methods being invoked implicitly in adding and retrieving objects from a Map:

Java equals vs hashCode

Java equals vs hashCode

The above example uses a custom key class MyKey that takes “name” and “date” as attributes. So, this key class needs to implement equals() and hashCode() methods using these 2 attributes.

a & b) When you put an object into a map with a key and a value, hashCode() method is implicitly invoked, and hash code value say 123 is returned. Two different keys can return the same hash value. A good hashing algorithm spreads out the numbers. In the above example, let’s assume that (“John”,01/01/1956) key and (“Peter”, 01/01/1995) key return the same hash value of 123.

Q. So, when we retrieve the object with a specific key, how does it know which one of two objects to return?
A. This is where the equals() method is implicitly invoked to get the object value with the right key. So, it needs to loop through each key/value pair in the bucket “123” to find the right key by comparing “name” & “date” via equals() method.

Q. What if you change the hashCode() method of the “MyKey” class to always return a constant value of? Will you be able to add objects to the map?
A. Yes, you will be able to add objects, but all the key/value pairs will be added to the single bucket, and the equals() method needs to loop through all the objects in the same bucket.

hashCode() returns 1

hashCode() returns 1

1 & 2). The hashCode() method picks the right bucket 123. Then loop through all the values and invoke the equals() method to pick the right key, which is (“John”,01/01/1956).

Q4. If a class overrides the equals( ) method, what other method it should override? What are some of the key considerations while implementing these methods?
A4. It should override the hashCode( ) method. The contract between the hashCode( ) and equals( ) methods is clearly defined on the Java API for the Object class under respective methods. Here are some key points to keep in mind while implementing these methods,

1) The equals( ) and hashCode( ) methods should be implemented together. You should not have one without the other.

2) If two objects return the same hashCode( ) integer value does not mean that those two objects are equal.

3) If two objects are equal, then they must return the same hashCode( ) integer value.

4) The implementation of the equals( ) method must be consistent with the hashCode( ) method to meet the previous bullet points.

5) Use @override annotation to ensure that the methods are correctly overridden.

6) Favor instanceof instead of getClass(..) in the equals( ) method which takes care of super types and null comparison as recommended by Joshua Bloch, but ensure that the equals implementation is final to preserve the symmetry contract of the method: x.equals(y) == y.equals(x). If final seems restrictive, carefully examine to see if overriding implementations can fully maintain the contract established by the Object class.

7) Check for self-comparison and null values where required.

Use Apache’s HashCodeBuilder & EqualsBuilder classes to simplify your implementation, especially when you have a large number of member variables. Commonclipse is an eclipse plugin for jakarta commons-lang users. It is very handy for automatic generation of toString( ), hashCode( ), equals(..), and compareTo( ) methods.

toString() method

Q5. Why or when should you override a toString( ) method?
A5. You can use System.out.println( ) or logger.info(…) to print any object. The toString( ) method of an object gets invoked automatically, when an object reference is passed in the System.out.println(refPet) or logger.info(refPet) method. However for good results, your class should have a toString( ) method that overrides Object class’s default implementation by formatting the object’s data in a sensible way and returning a String. Otherwise all that’s printed is the class name followed by an “@” sign and then unsigned hexadecimal representation of the hashCode. For example, If the Pet class doesn’t override the toString( ) method as shown below, by default Pet@162b91 will be printed via toString( ) default implementation in the Object class.

Q6. Can you override clone( ) and finalize( ) methods in the Object class? How do you disable a clone( ) method?
A6. es, but you need to do it very judiciously. Implementing a properly functioning clone( ) method is complex and it is rarely necessary. You are better off providing some alternative means of object copying through a copy constructor or a static factory method.

Unlike C++ destructors, the finalize( ) method in Java is unpredictable, often dangerous and generally unnecessary. Use finally{} blocks to close any resources or free memory. The finalize( ) method should only be used in rare instances as a safety net or to terminate noncritical native resources. If you do happen to call the finalize( ) method in some rare instances, then remember to follow the following guidelines:

1) You should call the finalize method of the super class in case it has to clean up.

2) You should not depend on the finalize method being called. There is no guarantee that when (or if) objects will be garbage collected and thus no guarantee that the finalize method will be called before the running program terminates.

3) Finally, the code in finalize method might fail and throw exceptions. Catch these exceptions so that the finalize method can continue.

How do you disable a clone( ) method?


300+ Core Java Interview Q&As
Module 1 Java Overview+
Unit 1 17 Java Overview Interview Q&As  - Preview
Unit 2 4 Java Compile-time Vs Runtime Interview Q&As  - Preview
Module 2 Java data types+
Unit 1 8 Java data types interview Q&As  - Preview
Unit 2 7 Java primitives & objects memory consumption Q&As  - Preview
Unit 3 4 Java autoboxing & unboxing interview Q&As  - Preview
Unit 4 12 Java String class Interview Q&As  - Preview
Module 3 Java modifiers, annotations, initializers & constructors+
Unit 1 6 Java Modifiers every interviewer seems to like  - Preview
Unit 2 10 Java initializers, constructors, regular methods and static factory methods Q&As
Unit 3 8 Java Annotations interview Q&As
Unit 4 4 Java annotation types & processing interview Q&As
Module 4 Java classes, interfaces & class loaders+
Unit 1 12 Java classes and interfaces interview Q&As
Unit 2 3 Abstract classes Vs interfaces interview Q&As
Unit 3 3 Java class loading interview Q&As to ascertain your depth of Java knowledge
Module 5 Java Objects Interview Q&As-
Unit 1 5 Java Object class methods interview Q&As  - Preview
Unit 2 3 Object wait( ) & notify( ) interview Q&As
Unit 3 7 Object equals Vs == and pass by reference Vs value interview Q&As
Unit 4 10 Java immutable objects interview Q&As
Unit 5 10 Java serialization, cloning, and casting interview Q&As
Module 6 OOP & FP+
Unit 1 10 Java OOP Interview Q&As
Unit 2 5 Inheritance Vs Composition OOP Interview Q&As  - Preview
Unit 3 2 Polymorphism OOP Interview Q&As
Unit 4 8 OOP Design principles interview Q&As
Unit 5 5 OOP Vs FP, FP concepts & where to use FP Q&As  - Preview
Unit 6 19 Java Functional Programming (i.e. FP) interview Q&As
Unit 7 Java FP Lambda expressions by examples
Module 7 Generics & Java Collection Framework(JCF)+
Unit 1 12 Java Generics Interview Q&As  - Preview
Unit 2 5 Java Generics Wildcards Interview Q&As
Unit 3 17 Java Collection Framework (JCF) interview Q&As
Unit 4 9 Java data structures interview Q&As
Unit 5 4 Sorting objects in a Collection interview Q&As
Unit 6 8 Java Map interface & Caching interview Q&As
Unit 7 Lambda expressions to work with Java 8 Collections
Module 8 Java multithreading+
Unit 1 17 Java multi-threading interview Q&As  - Preview
Unit 2 7 Java locks & synchronized keyword interview Q&As
Unit 3 9 blocking, scheduling & daemon threads interview Q&As
Unit 4 7 Java Executor framework Interview Q&As
Unit 5 ExecutorService Vs Fork/Join & Future Vs CompletableFuture Interview Q&As
Unit 6 7 Java ThreadLocal interview Q&As
Unit 7 Java Thread stop, resume, suspend & interrupt interview Q&As
Unit 8 12 Java multi-threading differences between X and Y Q&As
Unit 9 Java multi-threading 15 scenarios interview Q&As
Module 9 What is wrong with this multithread code?+
Unit 1 5 Ways to debug Java thread-safety issues  - Preview
Unit 2 Heap Vs Stack, Thread safety & Synchronization  - Preview
Unit 3 Deep Vs Shallow comparison & multithreading
Unit 4 An excellent written test multithreading question - wait/notify
Unit 5 Multithreading & Locks
Unit 6 Java Collection & ConcurrentModificationException
Unit 7 HashMap & Race condition
Unit 8 ConcurrentHashMap & Atomic operations
Unit 9 JConsole for debugging deadlocks in Java
Unit 10 jvisualvm to debug deadlocks in Java
Module 10 Exceptions Handling+
Unit 1 5 Java exception handling interview Q&As
Module 11 Java I/O & NIO+
Unit 1 15 Java old I/O and NIO (i.e. New I/O) interview Q&As
Unit 2 Java 8 way to reading files
Module 12 JVM+
Unit 1 11 JVM memory model and Atomicity, Visibility, and Ordering interview Q&As
Unit 2 8 Java Garbage Collection interview Q&As to ascertain your depth of Java knowledge
Unit 3 jvisualvm to sample Java heap memory
Unit 4 5 JMX and MBean interview Q&As
Module 13 What is new?+
Unit 1 Java 7 features list
Unit 2 Java 8 features list
Module 14 Java code quality+
Unit 1 How will you go about improving on the following Java code?
Unit 2 How will you go about ensuring code quality in Java apps?
Unit 3 5 Java unit testing interview Q&As
Unit 4 Mocks, stubs, domain, and anemic objects interview Q&As
Unit 5 30+ Java Code Review Checklist Items
Module 15 Debugging Java applications+
Unit 1 7 debugging Java interview questions & answers
Unit 2 Debugging "NoSuchMethodError" in Java
Unit 3 Debugging JAR hell issues in Java
Unit 4 Debugging Java version issues
Unit 5 Remote debugging in Java with Java Debug Wire Protocol (JDWP)
Unit 6 Debugging like a pro with eclipse IDE tutorial for Java developers
Module 16 Performance considerations & memory management+
Unit 1 4 Java application performance considerations interview Q&As
Unit 2 8 Java memory management interview Q&As
Unit 3 jvisualvm to detect memory leak
Module 17 Design Patterns Interview Q&As+
Unit 1 12 Java design patterns interview Q&As
Unit 2 5 Java singleton design pattern interview Q&As
Unit 3 Java Proxy, Decorator, Adapter, Bridge, and Facade design patterns Interview Q&As
Unit 4 3 Flyweight design pattern Interview Q&As to improve memory usage & performance
Learn by categories on the go...
Learn by categories such as FAQs – Core Java, Key Area – Low Latency, Core Java – Java 8, JEE – Microservices, Big Data – NoSQL, Architecture – Distributed, Big Data – Spark, etc. Some posts belong to multiple categories.
Top