Explore topic-wise InterviewSolutions in .

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»
HashMapTreeMap
The Java HashMap implementation of the MAP interface is BASED on hash tables.Java TreeMap is a Map interface implementation based on a Tree structure.
The Map, Cloneable, and Serializable interfaces are implemented by HashMap.NavigableMap, Cloneable, and Serializable interfaces are implemented by TreeMap.
Because HashMap does not order on keys, it allows for heterogeneous elements.Because of the sorting, TreeMap allows homogenous values to be USED as a key.
HashMap is quicker than TreeMap because it offers O(1) constant-time performance for basic OPERATIONS such as to get() and put().TreeMap is slower than HashMap because it performs most operations with O(log(n)) performance, such as add(), remove(), and contains().
A SINGLE null key and numerous null values are allowed in HashMap.TreeMap does not allow null keys, however multiple null values are allowed.
To compare keys, it uses the Object class's equals() method. It is overridden by the Map class's equals() function.It compares keys using the compareTo() method.
HashMap does not keep track of any sort of order.The elements are arranged in chronological sequence (ascending).
When we don't need a sorted key-value pair, we should use the HashMap. When we need a key-value pair in sorted (ascending) order, we should use the TreeMap.
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 :

  • Vector is SLIGHTLY slower than ArrayList due to the fact that it is synchronized and thread-safe.
  • Vector's functionality is that it synchronizes each individual action. A programmer's preference is to SYNCHRONIZE an entire sequence of actions. Individual operations are less safe and take longer to synchronize.
  • Vectors are considered outdated in Java and have been unofficially deprecated. Vector also synchronizes on a per-operation basis, which is almost never done. Most java programmers PREFER to use ArrayList since they will almost certainly synchronize the arrayList explicitly if they need to do so.
4.

How can you synchronize an ArrayList in Java?

Answer»

An ArrayList can be synchronized using the following two ways :

  • Using Collections.synchronizedList() method:
    All access to the BACKUP list must be done through the returning list in order to perform serial access. When iterating over the returned list, it is critical that the user manually synchronizes.
    Example:
import java.util.*; class InterviewBit{ public static void main (String[] ARGS) { List&LT;String> synchronized_list = Collections.synchronizedList(new ArrayList<String>()); synchronized_list.ADD("learn"); synchronized_list.add("practice"); synchronized_list.add("solve"); synchronized_list.add("interview"); synchronized(synchronized_list)// must be declared { Iterator it = synchronized_list.iterator(); while (it.hasNext()) System.out.println(it.next()); } }}

Output:

learnpracticesolveinterview
  • Using CopyOnWriteArrayList:

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:

  • HashMap is a non-synchronized DATA structure. It is not thread-safe and cannot be SHARED across many THREADS without the use of synchronization code, while Hashtable is synchronized. It's thread-safe and can be used by several threads.
  • HashMap supports one null key and numerous null values, whereas Hashtable does not.
  • If thread synchronization is not required, HashMap is often PREFERABLE over 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.

IteratorEnumeration
Iterator is a universal cursor since it works with all collection classes.Because it only applies to legacy classes, enumeration is not a universal cursor.
Iterators can make changes (for example, the delete() method removes an element from a Collection during traversal).The Enumeration interface is a read-only interface, which means you can't make any changes to the Collection while traversing its elements.
The remove() method is available in the Iterator class.The remove() method is not available in the enumeration.
Iterator is not a legacy interface. Iterator can traverse HashMaps, LinkedLists, ArrayLists, HashSets, TreeMaps, and TreeSets.Enumeration is a legacy interface for traversing Hashtables and Vectors.
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.

Fail-FastFail-Safe
These types of iterators do not allow MODIFYING the collection while iterating over it.These types of iterators allow modifying the collection while iterating over it.
It throws ConcurrentModificationException if the collection is modified while iterating over it.No exception is thrown if the collection is modified while iterating over it.
It uses the original collection while traversing the elements.It uses a copy of the original collection while traversing over it.
No extra memory is required in this CASE.Extra memory is required in this case.
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»
COMPARABLEComparator
A single sorting sequence is provided by Comparable. To put it another way, we can sort the collection by a single attribute such as id, NAME, or price.Multiple sorting sequences are available in the Comparator. To put it another way, we can sort the collection based on different criteria such as id, name, and price.
To sort elements, Comparable provides the compareTo() method.To order elements, the Comparator provides the compare() method.
It is PRESENT in the java.lang package.It is present in the java.util package.
The original class is affected by Comparable, i.e. the real class is changed. The original class is UNAFFECTED by the comparator, i.e. the real class is unaffected.
The Collections.sort(LIST) method can be used to sort Comparable type list members.The Collections.sort(List, Comparator) method can be used to sort the list components of the Comparator type.