This article provides interview questions for experienced Java professionals.
The invocation of an Object’s finalize() method is the last thing that happens before an object is garbage collected. True or False ?
First the object is collected and then it is finalized.
Here is the Object lifecycle for reference:
- In use (strongly reachable)
Is putting clean up code in finalize() a good idea ?
Will the finalize() method be always called before execution of Garbage Collector method?
Is there a way to enforce finalize() method ?
finalize() is supposed to happen right before the object is cleaned up. But the finalize method may never actually get called, so any critical clean-up code that definitely needs to run should go somewhere else.. Don’t count on finalize to clean up, just do the cleaning yourself before the object loses its scope.
Why value classes such as Integer, AtomicInteger, BigDecimal, Double should implement Serializable?
Serialization is a mechanism where an object can be represented as a sequence of bytes that includes the object’s data as well as information about the object’s type and the types of data stored in the object.
Adding Serializable marks them having exactly the described functionality. This allows you to stream your class in a file and read it again from the file.
If parent of a serializable class doesn’t implement serializable, will the parent be serialized automatically?
The subclass may assume responsibility for saving and restoring the state of the superclass’s public, protected, and (if accessible) package fields. This means that by default these values will be established by calling super() no argument constructor. It is however possible that you may need these to be serialized (and deserialized) in which case the responsibility is yours.
The subclass may assume this responsibility only if the class it extends has an accessible no-arg constructor to initialize the class’s state.
Two objects with same hashcode are inserted inside a hashmap. Now, how many objects will be there inside the hashmap?
If two elements have different hashcodes then they are different. When two elements have the same hashcode then Java uses the equals to further differentiate the elements. So the answer is one or two objects depending on the equals() method.
In general, in order to use HashMap collection, it’s necessary to override equals() and hashCode(). Do we need to override equals() and hashCode() for String, Integer, and other primitive classes in HashMap?
No. Strings (and Integers) already implement equals and hashCode, and there’s no way you can override it for them since those classes are final, hence not extensible.
© 2016, https:. All rights reserved. On republishing this post, you must provide link to original post