InterviewSolution
This section includes InterviewSolutions, each offering curated multiple-choice questions to sharpen your knowledge and support exam preparation. Choose a topic below to get started.
| 1. |
Differentiate between HashMap and TreeMap in the context of Java. |
||||||||||||||||||
Answer»
|
|||||||||||||||||||
| 2. |
Why does not the Map interface extend the Collection Interface or vice-versa? |
|
Answer» If Map extends the Collection Interface, "Key-value pairs" can be the only element type for this type of Collection, although this provides a very limited (and not really useful) Map abstraction. You can't inquire what value a specific key corresponds to, and you can't delete an entry without knowing what value it corresponds to. The three "Collection view PROCEDURES" on MAPS REPRESENT the fact that Maps can be viewed as COLLECTIONS (of keys, values, or pairs) (keySet, entrySet, and values). While it is theoretically feasible to see a List as a Map mapping indices to items, this has the unfortunate side effect of CHANGING the Key associated with every element in the List prior to the deleted member. This is the reason why Collection can not be made to extend the Map Interface either. |
|
| 3. |
Why do we need synchronized ArrayList when we have Vectors (which are synchronized) in Java? |
|
Answer» Following are the reasons why we need SYNCHRONIZED ArrayLists even THOUGH we have Vectors :
|
|
| 4. |
How can you synchronize an ArrayList in Java? |
|
Answer» An ArrayList can be synchronized using the following two ways :
Output: learnpracticesolveinterview
Syntax: CopyOnWriteArrayList<T> list_name = new CopyOnWriteArrayList<T>();Here, a thread-safe variant of ArrayList is created. T represents generic. All mutative actions (e.g. add, set, remove, etc.) are implemented by generating a separate copy of the underlying array in this thread-safe variation of ArrayList. It accomplishes thread safety by generating a second copy of List, which differs from how vectors and other collections achieve thread-safety. Even if copyOnWriteArrayList is modified after an iterator is formed, the iterator does not raise CONCURRENTMODIFICATIONEXCEPTION because the iterator is iterating over a separate copy of ArrayList while a write operation is occurring on another copy of ArrayList. Example: import java.io.*;import java.util.Iterator;import java.util.concurrent.CopyOnWriteArrayList; class InterviewBit{ public static void main (String[] args) { CopyOnWriteArrayList<String> synchronized_list = new CopyOnWriteArrayList<String>();// creating a thread-safe Arraylist. // Adding strings to the synchronized ArrayList synchronized_list.add("learn"); synchronized_list.add("practice"); synchronized_list.add("solve"); synchronized_list.add("interview"); System.out.println("The synchronized ArrayList has the following elements :"); // Iterating on the synchronized ArrayList using an iterator. Iterator<String> it = synchronized_list.iterator(); while (it.hasNext()) System.out.println(it.next()); }}Output: The synchronized ArrayList has the following elements :learnpracticesolveinterview |
|
| 5. |
Why does HashMap allow null whereas HashTable does not allow null? |
|
Answer» The OBJECTS used as keys must IMPLEMENT the hashCode and equals methods in order to SUCCESSFULLY SAVE and retrieve objects from a HashTable. These methods cannot be implemented by null because it is not an object. HashMap is a more advanced and IMPROVED variant of Hashtable.HashMap was invented after HashTable to overcome the shortcomings of HashTable. |
|
| 6. |
Differentiate between HashMap and HashTable. |
|
Answer» FOLLOWING are the differences between HashMap and HashTable:
|
|
| 7. |
What is the use of Properties class in Java? What is the advantage of the Properties file? |
|
Answer» The KEY and value pair are both strings in the properties object. The java.util.Properties class is a Hashtable subclass. It can be used to calculate the value of a property based on its key. The Properties class has methods for reading and writing data to and from the properties file. It can also be used to obtain a system's attributes. Advantage of the Properties file: If the INFORMATION in a properties file is modified, no recompilation is required: You don't need to recompile the java class if any information in the properties file changes. It is used to keep track of information that needs to be updated frequently. Example: Let us first create a properties file named “info.properties” having the following content : user = success PASSWORD = determination Let us now create a java class to read data from the properties file import java.util.*; import java.io.*; public class Sample { public static void main(String[] args)THROWS EXCEPTION{ FileReader reader = new FileReader("info.properties"); Properties obj_p = new Properties(); obj_p.load(reader); System.out.println(obj_p.getProperty("user")); System.out.println(obj_p.getProperty("password")); } }Output: successdetermination |
|
| 8. |
Differentiate between Iterator and Enumeration. |
||||||||||
|
Answer» Iterator: Because it can be applied to any Collection object, it is a UNIVERSAL iterator. We can EXECUTE both read and remove operations using Iterator. It's an ENHANCED version of Enumeration that adds the ability to remove an element from the list. Enumeration: An enumeration (or enum) is a data type that is defined by the user. It's mostly used to give integral constants names, which make a program EASIER to COMPREHEND and maintain. Enums are represented in Java (since 1.5) through the enum data type.
|
|||||||||||
| 9. |
What is the purpose of RandomAccess Interface? Name a collection type which implements this interface. |
|
Answer» RandomAccess, like the Serializable and Cloneable interfaces, is a marker interface. There are no methods defined in any of these marker interfaces. RATHER, they designate a class as having a SPECIFIC capability. The RandomAccess interface indicates whether or not a given java.util.List implementation supports RANDOM access. This interface seeks to define a vague concept: what does it mean to be fast? A simple guide is provided in the documentation: The List has fast random access if repeated access using the List.get( ) method is FASTER than repeated access using the ITERATOR.next( ) method. Repeated access using List.get( ): Object obj;for (int i=0, n=list.size( ); i < n; i++) obj = list.get(i);Repeated access using Iterator.next( ): Object obj;for (Iterator itr=list.iterator( ); itr.hasNext( ); ) obj = itr.next( ); |
|
| 10. |
Explain fail-fast and fail-safe iterators. Differentiate between them. |
||||||||||
|
Answer» If the collection's structure is changed, Fail-Fast iterators immediately throw ConcurrentModificationException. While a thread is iterating over a collection, structural ALTERATION includes adding or deleting any element. Fail-safe Iterator classes include ArrayList Iterator and HashMap Iterator. Fail-fast iterators use an internal indicator CALLED modCount, which is updated each time a collection is modified, to determine if the collection has been structurally modified or not. When a fail-fast iterator gets the next item (through the next() method), it checks the modCount flag, and if it discovers that the modCount has been changed after the iterator was generated, it throws a ConcurrentModificationException. If a collection is structurally updated while iterating over it, fail-safe iterators don't throw any exceptions. Because they operate on a clone of the collection rather than the original collection, they are REFERRED to as fail-safe iterators. Fail-safe Iterators include the CopyOnWriteArrayList and ConcurrentHashMap classes.
|
|||||||||||
| 11. |
What do you understand about BlockingQueue in Java? |
|
Answer» BlockingQueue is an INTERFACE that has been included along with a number of other concurrent Utility classes such as ConcurrentHashMap, Counting Semaphore, CopyOnWriteArrayList, and so on. In addition to queueing, the BlockingQueue interface enables flow control by adding blocking if either BlockingQueue is full or EMPTY. A THREAD attempting to enqueue an element in a full queue will be blocked until another thread clears the queue, either by dequeuing ONE or more elements or by clearing the queue entirely. It also prevents a thread from deleting from an empty queue until another thread inserts an item. A null value is not accepted by BlockingQueue. Implementations of the Java BlockingQueue interface are thread-safe. BlockingQueue's methods are all atomic and use internal locks or other forms of concurrency management. There are two types of BlockingQueue in Java. They are as follows : Unbounded Queue: The blocked queue's capacity will be set to Integer. MAX VALUE. An unbounded blocking queue will never block since it has the potential to grow to a very big SIZE. As you add more pieces, the size of the queue grows. Example : BlockingQueue unbounded_queue = new LinkedBlockingDeque();Bounded Queue: The bounded queue is the second type of queue. In the case of a bounded queue, the capacity of the queue can be passed to the constructor when the blocking queue is created. Example: // Creates a Blocking Queue with capacity 10BlockingQueue bounded_queue = new LinkedBlockingDeque(10); |
|
| 12. |
Differentiate between Comparable and Comparator in the context of Java. |
||||||||||||
Answer»
|
|||||||||||||