| Page | 1 | 2 | 3 | 4 |
Q1. What is the difference between Comparable and Comparator?
When Comparable is used you need to implement compare(Object Other) method and this method drives the natural ordering of the objects, while in case of Comparator, equals(Object o) method drives the ordering. In Comparator the implementor has to implement compare(T o1, T o2) method. Comparator does the comparison between two objects while Comparable does the comparison from other object to the one who is comparable.
Q2. What data structure is well suited to implement LRU cache?
LinkedHashMap with accessOrder value as true is usually used for this purpose. To impose the size constraints you need to implement removeEldestEntry (Map.Entry<K,V> eldest) method. Remember, LinkedHashMap is not synchronized and so you need to make your getter and setter synchronized to have consistent data.
Q3. What does final, finally and finalize signify?
final is a reserved keyword and makes an entity non over-ridable once attached to it. i.e. final variable's value can't be changed(or basically override), final method can't be overridden, and final class can't have subclasses. finalize is a method and used on the objects whose memory shall be reclaimed by Garbage collector. finally is a block used in try block to make some final things must to happen.
Q4. When you create a try, catch, finally block, what statement written in try block can prevent finally block to execute?
System.exit(1). The only way is to come out of the JVM. System.exit(1) shall terminate the running JVM and so finally block shall not be executed. This stage can also be reached by writing an infinite loop inside the try block.
Q5. What is OOM? When it comes?
OOM(Out Of Memory) is an error. When JVM is not able to allocate any memory to an object on the heap, OOM is thrown. JVM ensures that there were no memory left when this error is thrown. OOM could be of three type.