Java Collection Interview Questions

Java Collection Interview Questions: Java collections are a set of classes and interfaces provided by Java to manipulate data in various ways, such as storing and retrieving data in arrays, lists, and maps. Java collections are crucial to Java programming and are widely used in Java-based enterprise applications. As such, Java Collection interview questions are crucial to Java developer interviews.

These interview questions are designed to assess a candidate’s knowledge and proficiency in using Java collections, including their advantages and disadvantages, the different types of collections, and their practical applications in programming. In this context, this article presents some commonly asked Java Collection interview questions that can help Java developers prepare for interviews and better understand the Java collection framework.

Java Collections Interview Questions In Java: If you go for an interview, then you must face some of the below Java collection interview questions, and these questions can help all candidates, like freshers and experienced guys.

Java Collection Interview Questions For Experienced

  • What are the differences between the two data structures: a Vector and an ArrayList?
  • What are the differences between Collection and Collections in Java?
  • In which scenario is LinkedList better than ArrayList in Java?
  • What are the differences between a List and a Set collection in Java?
  • What are the differences between a HashSet and TreeSet collection in Java?
  • In Java, how will you decide when to use a List, Set, or Map collection?
  • What are the differences between a HashMap and a Hashtable in Java?
  • What are the differences between a HashMap and a TreeMap?
  • What are the differences between Comparable and Comparator?
  • In Java, what is the purpose of the Properties file?
  • What is the reason for overriding the equals() method?
  • How does the hashCode() method work in Java?
  • Is it a good idea to use Generics in collections?
  • What is the difference between Collection and Collections Framework in Java?
  • What are the main benefits of the Collections Framework in Java?
  • What is the root interface of the Collection hierarchy in Java?
  • What are the main differences between Collection and Collections?
  • What are the Thread-safe classes in the Java Collections framework?
  • How will you efficiently remove elements while iterating a Collection?
  • How will you convert a List into an array of integers like- int[]?
  • How will you convert an array of primitive integers int[] to a List collection?
  • How will you run a filter on a Collection?
  • How will you convert a List to a Set?
  • How will you remove duplicate elements from an ArrayList?
  • How can you maintain a Collection with elements in Sorted order?
  • What is the difference between Collections.emptyList() and creating a new instance of Collection?
  • How will you copy elements from a Source List to another list?
  • What are the Java Collection classes that implement the List interface?
  • What are the Java Collection classes that implement the Set interface?
  • What is the difference between an Iterator and a ListIterator in Java?
  • What is the difference between Iterator and Enumeration?
  • What is the difference between an ArrayList and a LinkedList data structure?
  • What is the difference between a Set and a Map in Java?
  • What is the use of a Dictionary class?
  • What is the default size of the load factor in a HashMap collection in Java?
  • What is the significance of load factor in a HashMap in Java?
  • What are the major differences between a HashSet and a HashMap?
  • What are the similarities between a HashSet and a HashMap in Java?
  • What is the reason for overriding the equals() method?
  • How can we synchronize the elements of a List, a Set, or a Map?
  • What is Hash Collision? How Java handles hash-collision in HashMap?
  • What are the Hash Collision resolution techniques?
  • What is the difference between Queue and Stack data structures?
  • What is an Iterator in Java?
  • What is the difference between Iterator and Enumeration in Java?
  • What is the design pattern used in the implementation of Enumeration in Java?
  • Which methods do we need to override to use an object as a key in a HashMap?
  • How will you reverse a List in Java?
  • How will you convert an array of String objects into a List?
  • What is the difference between the peek(), poll(), and remove() methods of the Queue interface in Java?
  • What is the difference between Array and ArrayList in Java?
  • How will you insert, delete, and retrieve elements from a HashMap collection in Java?
  • What are the main differences between HashMap and ConcurrentHashMap in Java?
  • What is the increasing order of performance for the following collection classes in Java?
  • Why does the Map interface not extend the Collection interface in Java?
  • What are the different ways to iterate elements of a list in Java?
  • What is CopyOnWriteArrayList? How is it different from ArrayList in Java?
  • How is the remove() method implemented in a HashMap?
  • What is BlockingQueue in Java Collections?
  • How is the TreeMap class implemented in Java?
  • What is the difference between Fail-fast and Fail-safe iterators in Java?
  • How does ConcurrentHashMap work in Java?
  • What is the importance of hashCode() and equals() methods?
  • What is the contract of hashCode() and equals() methods in Java?
  • What is an EnumSet in Java?
  • What are the main Concurrent Collection classes in Java?
  • How will you convert a Collection to a Synchronized Collection in Java?
  • How is IdentityHashMap different from a regular Map in Java?
  • What is the main use of IdentityHashMap?
  • How can we improve the performance of IdentityHashMap?
  • Is IdentityHashMap thread-safe?
  • What is a WeakHashMap in Java?
  • How can you make a Collection class read Only in Java?
  • When is UnsupportedOperationException thrown in Java?
  • Let’s say there is a Customer class. We add objects of the Customer class to an array list. How can we sort the Customer objects in the array list by using the customer firstName attribute of the Customer class?
  • What is the difference between Synchronized Collection and Concurrent Collection?
  • What is the scenario for using ConcurrentHashMap in Java?
  • How will you create an empty Map in Java?
  • What is the difference between the remove() method of Collection and the remove() method of Iterator?
  • Between an Array and ArrayList, which one is the preferred collection for storing objects?
  • Is it possible to replace Hashtable with ConcurrentHashMap in Java?
  • How is the CopyOnWriteArrayList class different from the ArrayList and Vector classes?
  • Why does ListIterator have an add() method, but Iterator does not?
  • Why do we sometimes get ConcurrentModificationException during iteration?
  • How will you convert a Map to a List in Java?
  • How can we create a Map with reverse view and lookup in Java?
  • How will you create a shallow copy of a Map?
  • Why can we not create a generic array in Java?
  • What is a PriorityQueue in Java?
  • What are the important points to remember while using Java Collections Framework?
  • How can we pass a Collection as an argument to a method and ensure that the method will not be able to modify it?
  • Can you explain how HashMap works in Java?
  • Can you explain how HashSet is implemented in Java?
  • What is a NavigableMap in Java?
  • What is the difference between descendingKeySet() and descendingMap() methods of NavigableMap?
  • What is the advantage of NavigableMap over Map?
  • What is the difference between headMap(), tailMap(), and subMap() methods of NavigableMap?
  • How will you sort objects by Natural order in a Java List?
  • How can we get a Stream from a List in Java?
  • Can we get a Map from a Stream in Java?
  • What are the popular implementations of Deque in Java?

Java Collections Interview Questions

What are the limitations of Object arrays?
Ans: The limitations of Object arrays are that:

  • Arrays are fixed in size. Once an array object is created, it cannot be increased or decreased in size based on the requirement. Hence, arrays are not recommended if the size is not known in advance.
  • They can hold only homogeneous elements.
  • There is no underlying data structure for arrays, and hence, there is no readymade method support for arrays. So, for every requirement, the program has to explicitly code the relevant method. To overcome these problems, collections are recommended.

State the differences between arrays and collections.
Ans:

ArraysCollections
Arrays are fixed in size. Once created, we are not allowed to increase or decrease the size of an array.Collections are growable in nature and hence based on the requirements. We can increase or decrease the size.
From the memory point of view, the use of arrays is not recommended.From the memory point of view, collections are recommended.
From the performance point of view, the use of arrays is not recommended.From the performance point of view, the use of collections is recommended.
Arrays can hold only homogeneous elements.Collections can hold both homogeneous and heterogeneous elements.
Arrays can hold both primitives as well as objects.Collections can hold only objects.
There is no supported readymade method available for any requirement. The program has to compulsory code it explicitly.Support is available for every requirement of a readymade method. As programmers, we have to know how to use those methods, but we are not responsible for implementing them.

What is a Collection API?
Ans: The Collection API defines a set of classes and interfaces for representing a group of objects as a single entity.

What is a Collection framework?
Ans: The Collection Framework defines a set of classes and interfaces for representing a group of objects as a single entity.

State the difference between Collections and Collection.
Ans:
A collection is an interface that can represent a group of individual objects as a single entity. It acts as the root interface of the collection framework. Collections are utility classes that define several utility methods for collection-implemented class objects.

Explain about Collection interface.
Ans: The Collection Interface can be used to represent a group of objects as a single entity:

  • It acts as a root interface for the entire collection framework.
  • It defines the most commonly used methods that can be applied for any collection implemented class object

Explain about List interface.

Ans: The List interface is a child interface of the Collection interface. This can be used to represent a group of individual objects as a single entity where:

  • Duplicates are allowed and
  • The insertion order is preserved.

Explain about the Set interface.

Ans: The set interface is a child interface of the Collection interface. It can be used to represent a group of individual objects as a single entity where:

  • Duplicate objects are not allowed, and Insertion order is not preserved.

Explain about SortedSet interface.
Ans: It is a child interface of the Set interface. It can be used to represent a group of individual objects into a single entity where:

  • All the objects are arranged in some sorting order (Can be natural sorting order or customized) and
  • Duplicates are not allowed.

Explain about NavigableSet.
Ans: It is a child interface of SortedSet and provides several utility methods for navigation purposes:

  • It doesn’t allow duplicates,
  • Insertion order is preserved and
  • It is introduced in the 1.6 version.

Explain about Queue interface.
Ans: If we want to represent a group of individual objects prior to processing, we should use the Queue interface. It is the child interface of the Collection interface and was introduced in the 1.5 version.

Explain about the Map interface.
Ans: Remember, it is not a child Interface of the Collection Interface, and hence, Map and Collection Interfaces don’t have any relationship.

  • It can be used to represent a group of objects as key-value pairs.
  • Both keys and values should be objects.
  • Keys can t be duplicated but values can be duplicated.
  • It has been introduced in the 1.2 version.

Explain about SortedMap.
Ans: If we want to represent a group of objects as key-value pairs, where all the entries are arranged according to some sorting order of keys, then we should use SortedMap. It is a child interface of Map and was introduced in the 1.2 version.

Explain about NavigableMap.
Ans: It is a child interface of SortedMap that defines several methods for navigation purposes. It was introduced in the 1.6 version.

Explain about the ArrayList class.
Ans: An array list is a Collection that can represent a group of objects as a single entity.

  • It is an implemented class for the List interface.
  • Introduced in the 1.2 version.
  • The underlying data structure is a resizable or growable array.
  • The insertion order is preserved.
  • Duplicates are allowed.
  • Heterogeneous objects are allowed.
  • Null insertion is possible.
  • This class implements RandomAccess, Serializable, and Cloneable interfaces.
  • It is the best choice for retrieval purposes and worst if our frequent operation is insertion or deletion in the middle.

What is RandomAccess Interface?
Ans:

  • RandomAccess interface is a marker interface and it doesn’t contain any methods.
  • ArrayList and Vector classes implement this interface.
  • If a collection class implements the RandomAccess interface, then we can access any of its elements at the same speed.

Explain about the LinkedList class.
Ans: A linked list is a collection-implemented class that represents a group of objects as a single entity.

  • LinkedList is the implementation class for the List interface.
  • Introduced in the 1.2 version.
  • The underlying data Structure is DoubleLinkedList.
  • Allows duplicates.
  • The insertion order is preserved.
  • It allows for heterogeneous objects.
  • Null insertion is possible.
  • The linkedList class implements the Serializable and Cloneable interface but not the RandomAccess interface.
  • The best choice is if the frequent operation is insertion or deletion of an object in the middle, but the worst choice is if the frequent operation is retrieval.

Explain about the Vector class.
Ans: Vector is a legacy collection class that can be used to represent a group of objects.

  • Introduced in the 1.0 version. it is a legacy class.
  • The underlying data structure is a resizable or growable array.
  • Insertion order is preserved
  • Duplicates are allowed
  • Heterogeneous objects are allowed
  • It is an implemented class for the List interface
  • null insertion is possible
  • Vector class implements RandomAccess, Serializable, and Cloneable interfaces.
  • The best choice is if the frequent operation is retrieval, and the worst choice is if the frequent operation is insertion or deletion in the middle.
  • All methods present in the Vector class are synchronized; hence, the Vector class object is thread-safe.

What is the difference between ArrayList and Vector?
Ans:

ArrayListVector
No method is synchronized in the
ArrayList class
All methods in Vector are synchronized.
ArrayList object is not threaded safeThe vector is threaded safe.
Relatively performance is highRelatively performance is low
Introduced in the 1.2 version, it is a non-legacyIntroduced in the 1.0 version it is legacy

How can we get a synchronized version of ArrayList?
Ans: Collections class contains synchronizedList() method for this Public static List synchronizedList(List l)
Example:

ArrayList l= new ArrayList();
List l2=Collections.synchronizedList(l);

Similarly, we can get synchronized versions of Set and Map objects using the following methods.

Public static List synchronizedSet(Set s)
Public static List synchronizedMap(Map m)

What is the difference between the size and capacity of a Collection Object?
Ans: Size means the number of objects present, whereas capacity means no of objects it can accommodate.

What is the difference between ArrayList and Linked List?
Ans:

ArrayListLinkedList
The underlying data structure is a resizable or growable array.The underlying data structure is the Doubly Linked List.
This is the best choice if the frequent operation is retrieval and the worst choice if the frequent operation is
insertion or deletion in the middle.
This is the best choice if the frequent operation is insertion or deletion in the middle and the worst choice if the frequent operation is retrieval.
This class implements Serializable, Cloneable, and RandomAccess interfaces.This class implements a serializable and colloneable but not a random access interface.

What are legacy classes and interfaces present in the Collections framework?
Ans:

  • Enumeration —Interface
  • Dictionary ——Abstract class
  • Hashtable —–Concrete class
  • Properties —–Concrete class
  • Vector —–Concrete class
  • Stack —–Concrete class

What is the difference between Enumeration and Iterator?
Ans:

EnumerationIterator
It is a legacy interface and was introduced in the 1.0 versionIt is non-legacy and was introduced in the 1.2 version
Applicable only for legacy classes, and it is not a universal cursorApplicable for any Collection implemented class object.
While iterating the elements, we are not allowed to remove the objects just we can perform only read operationWhile iterating, we can also perform removal in addition to reading operations.
By using the elements() method, we can get the Enumeration objectBy using the iterator() method, we can get the Iterator object

What are the limitations of Enumeration?
Ans:

  • While iterating the elements, we are not allowed to perform removal operation
  • It is applicable only to legacy classes and is not a universal cursor.
  • It can retrieve the elements only in the forward direction

What is the difference between an enum and an Enumeration?
Ans: An enum can define a group of named constants. It was introduced in 1.5 versions.
Example:

Class Beer
{
	KO,KF,RC,FO
}

Enumeration is a cursor that retrieves objects one by one from collection objects.

What is the difference between Iterator and ListIterator?
Ans:

  • ListIterator is the child interface of the Iterator
  • Iterator is the single-direction cursor, whereas ListIterator is a bidirectional cursor.
  • While iterating the elements by Iterator, we can only perform read and remove operations. However, by using ListIterator, we can also perform read, removal, replace, and addition of new objects.
  • Iterator is applicable for every Collection-implemented class object, but ListIterator is applicable only for List-implemented class objects.
  • Iterator can be got by using iterator() of Collection interface whereas ListIterator can be got by using listIterator() method of List interface
  • Both are introduced in the 1.2 version

What is the relation between ListIterator and Iterator?
Ans: ListIterator is the child interface of Iterator

Explain about the HashSet class.
Ans:

  • The underlying data structure is Hashtable
  • Null values are accepted
  • Duplicates are not allowed
  • insertion order is based on the hashcode of the object hence, insertion order is not preserved
  • best suitable if the frequent operation is search operations
  • HashSet class implements Serializable and Cloneable
  • it is an implementation class for the Set interface
  • heterogeneous objects are allowed
  • it is introduced in the 1.2 version

If we are trying to insert duplicate values in Set what will happen?
Ans: If we are trying to insert duplicate objects into the HashSet, we won’t get any compile-time or run-time errors; just the add(Object o) returns false, and it doesn’t add that object.

What is LinkedHashSet?
Ans: It is the child class of HashSet. The main difference between HashSet and LinkedHashSet is: In the case of the HashSet insertion order is not preserved, but in the case of LinkedHashSet insertion will be preserved.

What are the differences between HashSet and LinkedHashSet?

Ans:

HashSetLinkedHashSet
The Underlying data structure is HashtableThe underlying data structure is a combination of LinkedList and Hashtable
Insertion Order is not preservedThe insertion order is preserved.
Introduced in the 1.2 versionIntroduced in the 1.4 version

What are the major enhancements in the 1.4 version of the collection framework?
Ans:

  • LinkedHashSet
  • LinkedHashMap
  • IdentityHashMap

Explain about TreeSet.
Ans: It is a collection object that can be used to represent a group of objects in some sorting order.

  • The underlying data structure is a Balanced tree
  • Duplicates are not allowed
  • All objects are stored according to some sorting order hence insertion order is not preserved
  • Heterogeneous objects are not allowed violation leads to ClassCastException
  • For an Empty TreeSet as the first element null value can be inserted, but after inserting that first value, if we are trying to insert any other objects, then we will get NullPointerException
  • For a non-empty TreeSet, if we are trying to insert a null value at run time, u will get NullPointerException

What are the differences between List and Set interfaces?
Ans:

ListSet
Insertion Order is preservedInsertion Order is not preserved
Duplicate Objects are allowedDuplicate Objects are not allowed
The implemented classes are ArrayList, LinkedList, Vector, and Stack classesThe implemented classes are HashSet, LinkedHashSet, and Tree

What is the Comparable interface?
Ans:

  • This interface can be used for defining the natural sorting order of the objects.
  • It is present in Java.lang package
  • It contains a method public int compareTo(Object obj1)

What is the Comparator interface?
Ans:

  • This interface can be used to implement a customized sorting order.
  • It is present in Java.util package
  • It contains two methods
    o public int compare(Object ,Object)
    o public boolean equals(Object)

What are the differences between Comparable and Comparator?
Ans:

ComparableComparator
This can be used for natural sorting orderThis can be used for implementing customized sorting
This interface present in java.lang packageThis is present in java.util package
Contains only one method: public int compareTo(Object obj1)It contains two methods. public int compare(Object,Object) & public Boolean equals(Object)
It is a marker interfaceIt is not a marker interface.

What is the difference between HashSet and TreeSet?
Ans:

HashSetTreeSet
The underlying data structure is HashtableThe underlying data structure is a balanced tree
Heterogeneous objects are allowedHeterogeneous objects are not allowed by default
Insertion order is not preserved, and it is based on the hashcode of the objectsInsertion order is not preserved, and all the objects are inserted according to some sorting order.
null insertion is possibleAs the first element, only null insertion is possible, and in all other cases, we will get
NullPointerException

What is the Entry interface?
Ans: The Entry Interface is the inner interface of Map. In the Map, each key-value pair is considered an Entry object.

interface Map
{
	//more code here
	interface Entry
	{
		Object getKey()
		Object getValue()
		Object setValue(Object new)
	}
}

Explain HashMap.
Ans: It is a Map Object that can be used to represent a group of objects as key-value pairs.

  • The underlying data structure is Hashtable
  • Duplicate keys are not allowed duplicate values are allowed
  • The insertion order is not preserved because insertion is based on the hashcode of keys.
  • Heterogeneous objects are allowed for both keys and values
  • the null key is allowed only once
  • null values are allowed multiple times
  • Introduced in the 1.2 version

Explain about LinkedHashMap.
Ans: It is a child class of HashMap. It is exactly the same as HashMap except for the following difference: In the case of HashMap, the insertion order is not preserved, but in the case of LinkedHashMap, the insertion order is preserved. It was introduced in the 1.4 version.

What are the differences between HashMap and LinkedHashMap?
Ans:

HashMapLinkedHashMap
The underlying data structure is HashtableThe underlying data structure is a combination of Hashtable and LinkedList
Insertion order is not preserved, and it is based on the hashcode of the keysInsertion order is preserved
Introduced in the 1.2 versionIntroduced in the 1.4 version.

Differences between HashMap and Hashtable?
Ans:

HashMapHashtable
The underlying data structure is HashtableThe underlying data structure of Hashtable
No method is synchronized and hence HashMap object is not threaded safeAll methods are synchronized and hence it is threaded safe
Performance is highPerformance is low
null insertion is possible for both keys and valuesnull insertion is not possible for both key and value violation leads to NullPointerException
Introduced in 1.2 version and it is a non-legacyIntroduced in 1.0 version and it is legacy

What is IdentityHashMap?
Ans: It is exactly the same as HashMap except for the following difference. In the HashMap JVM uses equals() method to identify duplicate keys but in the case of IdentityHashMap JVM uses == operator for this.

What is WeakHashMap?
Ans: It is exactly the same as HashMap except for the following difference. In the case of HashMap, an Object is not eligible for garbage collection if it is associated with HashMap even though it doesn’t have any external references. ie HashMap dominates garbage collector. But in the case of WeakHashMap, if an Object is not having any external references then it is always eligible for garbage collection even though it is associated with a weak hash map. i.e. garbage collector dominates WeakHashMap

What is TreeMap?
Ans: TreeMap can be used to store a group of objects as key-value pairs where all the entries are arranged according to some sorting order of keys.

  • The underlying data structure is RED-BLACK Tree
  • Duplicates keys are not allowed but values can be duplicated.
  • Insertion order is not preserved because insertion is based on some sorting order
  • If we are depending on Natural sorting order then keys should be homogeneous(violation leads to ClassCastException) but values need not homogeneous
  • In the case of customized sorting order, we can insert heterogeneous keys and values
  • For empty TreeMap as the first entry with null values are allowed but after inserting that entry if we are trying to insert any other entry we will get NullPointerException
  • For non-empty TreeMap if we are trying to insert null keys we will get NullPointerException
  • There are no restrictions for null values.

What is Hashtable?
Ans: Hashtable is a legacy Map and can be used to store objects as key-value pairs.

  • The underlying data structure is Hashtable
  • Duplicates keys are not allowed but duplicate values are allowed
  • null insertion is not possible for both keys and values
  • All methods are synchronized
  • Insertion order is not preserved because it is based on hashcode of keys
  • Heterogeneous Objects are allowed for both keys and values
  • Introduced in 1.0 version it is legacy class

What is a PriorityQueue?
Ans: It represents a data structure to hold a group of individual objects prior to processing based on some priority .it can be a natural sorting order and it can be customized sorting order described by Comparator. It is the implementation
class of Queue interface.

  • Insertion order is not preserved because here insertion is done based on some sorting order
  • Duplicates are not allowed
  • null insertion is not possible even as the first element also
  • If we are depending on natural sorting order Objects should be homogeneous violation leads to ClassCastException
  • If we are depending on customized sorting order Objects can be heterogeneous also.

What is the Arrays class?
Ans:

  • It is a utility class for arrays.
  • It defines several utility methods for arrays like sorting an array or searching an element in array
  • present in java. util package

We are planning to do an indexed search in a list of objects. Which of the two Java collections should you use: ArrayList or LinkedList?
Ans: ArrayList

Why ArrayList is faster than Vector?
Ans: All methods present in the Vector are synchronized and hence any method can be executed by only one thread at a time. It slows down the execution. But in ArrayList, no method is synchronized and hence multiple threads are allowed to execute simultaneously which speed up the execution.

What is an Iterator?
Ans: Some of the collection classes provide traversal of their contents via a java.util.Iterator interface. This interface allows you to walk through a collection of objects, operating on each object in turn. Remember when using Iterators that they contain a snapshot of the collection at the time the Iterator was obtained; generally, it is not advisable to modify the collection itself while traversing an Iterator.

What are HashMap and Map?
Ans: The map is an Interface and Hashmap is the class that implements Map.

Difference between HashMap and HashTable?
Ans: The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls. (HashMap allows null values as key and value whereas Hashtable doesn’t allow). HashMap does not guarantee that the order of the map will remain constant over time. HashMap is unsynchronized and Hashtable is synchronized.

Difference between Vector and ArrayList?

Ans: Vector is synchronized whereas ArrayList is not.

What is the Collections API?
Ans: The Collections API is a set of classes and interfaces that support operations on collections of objects.

Which characters may be used as the second character of an identifier, but not as the first character of an identifier?
The digits 0 through 9 may not be used as the first character of an identifier but they may be used after the first character of an identifier.

What is the List interface?
Ans: The List interface provides support for ordered collections of objects.

What is the Vector class?
Ans: The Vector class provides the capability to implement a growable array of objects.

What is an Iterator interface?
Ans: The Iterator interface is used to step through the elements of a Collection.

What is the Map interface?
Ans: The Map interface replaces the JDK 1.1 Dictionary class and is used to associate keys with values.

What is the Collection interface?
Ans: The Collection interface provides support for the implementation of a mathematical bag – an unordered collection of objects that may contain duplicates.

What is the Set interface?
Ans: The Set interface provides methods for accessing the elements of a finite mathematical set. Sets do not allow duplicate elements.

What is the difference between Array and vector?
Ans: The array is a set of related data types and static whereas vector is a growable array of objects and dynamic.

What are Vector, Hashtable, LinkedList, and Enumeration?
Ans: Vector: The Vector class provides the capability to implement a growable array of objects.

Hashtable: The Hashtable class implements a Hashtable data structure. Hashtable indexes and stores objects in a dictionary using hash codes as the object’s keys. Hash codes are integer values that identify objects.

LinkedList: Removing or inserting elements in the middle of an array can be done using LinkedList. A LinkedList stores each object in a separate link whereas an array stores object references in consecutive locations.

Enumeration: An object that implements the Enumeration interface generates a series of elements, one at a time. It has two methods, namely hasMoreElements() and nextElement(). HasMoreElemnts() tests if this enumeration has more elements and the nextElement method returns successive elements of the series.

What is the difference between the set and list?
Ans: Set stores elements in an unordered way but does not contain duplicate elements, whereas list stores elements in an ordered way but may contain duplicate elements.

Ref: article

If you found any questions which should be included in the list then you can inform that questions on the comment section and we will try to add that in our list with answers.

What is the difference between an Interface and an Abstract class?
Ans: An abstract class can have instance methods that implement a default behaviour. An Interface can only declare constants and instance methods, but cannot implement default behaviour, and all methods are implicitly abstract. An interface has all public members and no implementation. An abstract class is a class which may have the usual flavours of class members (private, protected, etc.), but has some abstract methods.

Q: What is the purpose of garbage collection in Java, and when is it used?
Ans: The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources can be reclaimed and reused. A Java object is subject to garbage collection when it becomes unreachable to the program in which it used.

Q: Describe synchronisation with respect to multithreading.
Ans: On multithreading, synchronisation is the capability to control the access of multiple threads to shared resources. Without synchronisation, one thread can modify a shared variable while another thread is in the process of using or updating the same shared variable. This usually leads to significant errors.

Q: Explain the different way of using thread?
Ans: The thread could be implemented by using runnable interface or by inheriting from the Thread class. Runnable Interface is more advantageous because when you are going for multiple inheritances, the only interface can help.

Q: What are pass by reference and pass by value?
Ans: Pass By Reference means the passing the address itself rather than passing the value. Pass by Value means passing a copy of the value to be passed.

Q: What are HashMap and Map?
Ans: Map is Interface and Hashmap is a class that implements that.

Q: Difference between HashMap and HashTable?
Ans: The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronised and permits nulls. (HashMap allows null values as a key, and value whereas Hashtable doesn’t allow). HashMap does not guarantee that the order of the map will remain constant over time. HashMap is unsynchronised, and Hashtable is synchronised.

Q: Difference between Vector and ArrayList?
Ans: Vector is synchronised whereas ArrayList is not.

Q: Difference between Swing and AWT?
Ans: AWT is heavyweight components. Swings are lightweight components. Hence swing works faster than AWT.

Q: What is the difference between a constructor and a method?
Ans: A constructor is a member function of a class that is used to create objects of that class. It has the same name as the class itself, has no return type, and is invoked using the new operator. A method is an ordinary member function of a class. It has its name, a return type (which may be void), and is invoked using the dot operator.

Q: What is an Iterator?
Ans: Some of the collection classes provide traversal of their contents via a java.util.Iterator interface. This interface allows you to walk through a collection of objects, operating on each object in turn. Remember when using Iterators that they contain a snapshot of the collection at the time the Iterator was obtained; generally it is not advisable to modify the collection itself while traversing an Iterator.

Q: State the significance of public, private, protected, default modifiers both singly and in combination and state
The effect of package relationships on declared items qualified by these modifiers.

  • Public: Public class is visible in other packages, a field is visible everywhere (class must be public too)
  • Private: Private variables or methods may be used only by an instance of the same class that declares the variable or method. A private feature may only be accessed by the class that owns the feature.
  • Protected: Is available to all classes in the same package and also available to all subclasses of the class that owns the protected feature. This access is provided even to subclasses that reside in a different package from the class that owns the protected feature.
  • Default: What you get by default, i.e., without any access modifier (i.e., public-private or protected).It means that it is visible to all within a particular package.

Q: What is an abstract class?
Ans: Abstract class must be extended/subclassed (to be useful). It serves as a template. An abstract class may not be instantiated (i.e., you may not call its constructor), abstract class may contain static data. Any class with an abstract method is automatically abstract itself and must be declared as such. A class may be declared abstract even if it has no abstract methods. This prevents it from being instantiated.

Q: What is static in java?
Ans: Static means one per class, not one for each object no matter how many instances of a class might exist. This means that you can use them without creating an instance of a class. Static methods are implicitly final, because overriding is done based on the type of the object, and static methods are attached to a class, not an object. A static method in a superclass can be shadowed by another static method in a subclass, as long as the original method was not declared final. However, you can’t override a static method with a nonstatic method. In other words, you can’t change a static method into an instance method in a subclass.

Q: What is the Final?
Ans: A final class can’t be extended, i.e., final class may not be subclassed. A final method can’t be overridden when its class is inherited. You can’t change the value of a final variable (is a constant).

Q: What if the main method is declared as private?
Ans: The program compiles properly, but at runtime, it will give “Main method not public.” message.

Q: What if the static modifier is removed from the signature of the main method?
Ans: Program compiles. But at runtime throws an error “NoSuchMethodError.”

Q: What if I write static public void instead of the public static void?
Ans: Program compiles and runs properly.

Q: What if I do not provide the String array as the argument to the method?
Ans: Program compiles but throws a runtime error “NoSuchMethodError.”

Q: What is the first argument of the String array in the main method?
Ans: The String array is empty. It does not have any element. This is unlike C/C++, where the first element by default is the program name.

Q: If I do not provide any arguments on the command line, then the String array of Main method will be empty or null?
Ans: It is empty. But not null.

Q: How can one prove that the array is not null but empty using one line of code?
Ans: Print args.length. It will print 0. That means it is empty. But if it would have been null, then it would have thrown a NullPointerException on attempting to print args.length.

Q: What environment variables do I need to set on my machine to be able to run Java programs?
Ans: CLASSPATH and PATH are the two variables.

Q: Can an application have multiple classes having the main method?
Ans: Yes, it is possible. While starting the application, we mention the class name to be run. The JVM will look for the Main method only in the class whose name you have mentioned. Hence there is no conflict amongst the multiple classes having the main method.

Q: Can I have multiple main methods in the same class?
Ans: No, the program fails to compile. The compiler says that the main method is already defined in the class.

Q: Do I need to import java.lang package any time? Why?
Ans: No. It is by default loaded internally by the JVM.

Read Also: Final VS Finally VS Finalize

Q: Can I import the same package/class twice? Will the JVM load the package twice at runtime?
Ans: One can import the same package or the same class multiple times. Neither compiler nor JVM complains abt it. And the JVM will internally load the class only once no matter how many times you import the same class.

Q: What are Checked and Unchecked Exception?
Ans: A checked exception is some subclass of Exception (or Exception itself), excluding class RuntimeException and its subclasses. Making an exception checked forces client programmers to deal with the possibility that the exception will be thrown. e.g., IOException has thrown by java.io.FileInputStream’s read() method•

Unchecked exceptions are RuntimeException and any of its subclasses. Class Error and its subclasses also are unchecked. With an unchecked exception, however, the compiler doesn’t force client programmers either to catch the exception or declare it in a throws clause. Client programmers may not even know that the exception could be thrown. E.g., StringIndexOutOfBoundsException thrown by String’s charAt() method• Checked exceptions must be caught at compile time. Runtime exceptions do not need to be. Errors often cannot be.

Q: What is Overriding?
Ans: When a class defines a method using the same name, return type, and arguments as a method in its superclass, the method in the class overrides the method in the superclass. When the method is invoked for an object of the class, it is the new definition of the method that is called and not the method definition from a superclass. Methods may be overridden to be more public, not more private.

Q: What are the different types of inner classes?
Ans: Nested top-level classes, Member classes, Local classes, Anonymous classes
Nested top-level classes, you declare a class within a class and specify the static modifier, the compiler treats the class just like any other top-level class.

Any class outside the declaring class accesses the nested class with the declaring class name acting similarly to a package. e.g., outer.inner. Top-level inner classes implicitly have access only to static variables. There can also be inner interfaces. All of these are of the nested top-level variety.

Member classes – Member inner classes are just like other member methods and member variables and access to the member class is restricted, just like methods and variables. This means a public member class acts similarly to a nested top-level
Class. The primary difference between member classes and nested top-level
classes are that member classes have access to the specific instance of the enclosing class.

Local classes – Local classes are like local variables, specific to a block of code. Their visibility is only within the block of their declaration. For the class to be useful beyond the declaration block, it would need to implement a more publicly available interface. Because local classes are not members, the modifiers public, protected, private, and static are not usable.

Anonymous classes – Anonymous inner classes extend local inner classes one level further. As anonymous classes have no name, you cannot provide a constructor.

Q: Are the imports checked for validity at compile time? e.g. will the code containing an import such asjava.lang.ABCD compile?
Ans: Yes, the imports are checked for the semantic validity at compile time. The code containing the above line of
import will not compile. It will throw an error saying, can not resolve symbol: class ABCD
location: package io
import java.io.ABCD;

Q: Does importing a package imports the subpackages as well? e.g. Does import com.MyTest.* also import com.MyTest.UnitTests.*?
Ans: No, you will have to import the sub-packages explicitly. It is importing com.MyTest.* will import classes in the package MyTest only. It will not import any class in any of its subpackages.

Q: What is the difference between declaring a variable and defining a variable?
Ans: In the declaration, we mention the type of the variable and its name. We do not initialise it. But defining means declaration + initialisation.
e.g. String s; is just a declaration while String s = new String (“abcd”); Or String s = “abcd”; are both definitions.

Q: What is the default value of an object reference declared as an instance variable?
Ans: null unless we define it explicitly.

Q: Can a top-level class be private or protected?
Ans: No. A top-level class can not be private or protected. It can have either “public” or no modifier. If it does not have a modifier, it is supposed to have a default access. If a top-level class is declared as private, the compiler will complain that the “modifier private is not allowed here”. This means that a top-level class can not be private.
Same is the case with protected.

Q: What type of parameter passing does Java support?
Ans: In Java, the arguments are always passed by value.

Q: Primitive data types are passed by reference or pass by value?
Ans: Primitive data types are passed by value.

Q: Objects are passed by value or by reference?
Ans: Java only supports pass by value. With objects, the object reference itself is passed by value and so both the original reference and parameter copy both refer to the same object.

Q: What is serialisation?
Ans: Serialization is a mechanism by which you can save the state of an object by converting it to a byte stream.

Q: How do I serialise an object to a file?
Ans: The class whose instances are to be serialised should implement an interface Serializable. Then you pass the instance to the ObjectOutputStream which is connected to a fileoutputstream. This will save the object to a file.

Q: Which methods of the Serializable interface should I implement?
Ans: The serializable interface is an empty interface; it does not contain any methods. So we do not implement any methods.
Q: How can I customise the serialisation process? i.e. how can one have control over the serialisation process?
Ans: Yes, it is possible to have control over the serialisation process. The class should implement the Externalizable interface. This interface contains two methods, namely readExternal and writeExternal. You should implement these methods and write the logic for customising the serialisation process.

Q: What is the common usage of serialisation?
Ans: Whenever an object is to be sent over the network, objects need to be serialised. Moreover, if the state of an object is to be saved, objects need to be serialised.

Q: What is the Externalizable interface?
Ans: Externalizable is an interface which contains two methods readExternal and writeExternal. These methods give you control over the serialisation mechanism. Thus if your class implements this interface, you can customise the serialisation process by implementing these methods.

Q: When you serialise an object, what happens to the object references included in the object?
Ans: The serialisation mechanism generates an object graph for serialisation. Thus it determines whether the included object references are serializable or not. This is a recursive process. Thus when an object is serialised, all the included objects are also serialised along with the original object.

Q: What one should take care of while serialising the object?
Ans: One should make sure that all the included objects are also serializable. If any of the objects are not serializable, then it throws a NotSerializableException

Q: What happens to the static fields of a class during serialisation?
Ans: There are three exceptions in which serialisation does not necessarily read and write to the stream. These are

  • Serialisation ignores static fields because they are not part of ay particular state.
  • Base class fields are only handled if the base class itself is serializable.
  • Transient fields.

Q: Does Java provide any construct to find out the size of an object?
Ans: No, there is not sizeof operator in Java. So there is not a direct way to determine the size of an object directly in
Java.

Q: Give the simplest way to find out the time a method takes for execution without using any profiling tool?
Ans: Read the system time just before the method is invoked and immediately after method returns. Take the time difference, which will give you the time taken by a method for execution.
To put it in code…
long start = System.currentTimeMillis ();
method ();
Long end = System.currentTimeMillis ();
System.out.println (“Time taken for execution is ” + (end-start));
Remember that if the time taken for execution is too small, it might show that it is taking zero milliseconds for execution. Try it on a method which is big enough, in a sense the one which is doing a considerable amount of processing.

Q: What are wrapper classes?
Ans: Java provides specialised classes corresponding to each of the primitive data types. These are called wrapper classes. They are, e.g. Integer, Character, Double etc.

Q: Why do we need wrapper classes?
Ans: It is sometimes easier to deal with primitives as objects. Moreover, most of the collection classes store objects and not primitive data types. And also the wrapper classes provide many utility methods. Because of these reasons we need wrapper classes. And since we create instances of these classes, we can store them in any of
the collection classes and pass them around as a collection. Also, we can pass them around as method parameters where a method expects an object.

Q: What are the checked exceptions?
Ans: Checked exception is those which the Java compiler forces you to catch. e.g. IOException has checked Exceptions.

Q: What are runtime exceptions?
Ans: Runtime exceptions are those exceptions that are thrown at runtime because of either wrong input data or because of wrong business logic etc. The compiler does not check these at compile time.

Q: What is the difference between error and an exception?
Ans: An error is an irrecoverable condition occurring at runtime. Such as OutOfMemory error. These JVM errors and you can not repair them at runtime. While exceptions are conditions that occur because of bad input etc.
e.g. FileNotFoundException will be thrown if the specified file does not exist. Or a NullPointerException will take
place if you try using a null reference. In most of the cases, it is possible to recover from an exception (probably by giving the user feedback for entering proper values, etc.).

Q: How to create custom exceptions?
Ans: Your class should extend class Exception or some more specific type thereof.

Q: If I want an object of my class to be thrown as an exception object, what should I do?
Ans: The class should extend from Exception class. Or you can extend your class from some more precise exception type also.

Q: If my class already extends from some other class, what should I do if I want an instance of my class to be thrown as an exception object?
Ans: One can not do anything in this scenario. Because Java does not allow multiple inheritances and does not provide any exception interface as well.

Q: How does an exception permeate through the code?
Ans: An unhandled exception moves up the method stack in search of a matching When an exception is thrown from a code which is wrapped in a try block followed by one or more catch blocks, a search is made for matching catch block. If a matching type is found, then that block will be invoked. If a matching type is not found, then the exception moves up the method stack and reaches the caller method. The same procedure is repeated if the caller method is included in a try-catch block. This process continues until a catch block handling the appropriate type of exception is found. If it does not find such a block, then finally the program terminates.

Q: What are the different ways to handle exceptions?
Ans: There are two ways to handle exceptions,

  • By wrapping the desired code in a try block followed by a catch block to catch the exceptions. and
  • List the desired exceptions in the throws clause of the method and let the caller of the method handle those exceptions.

Q: What is the basic difference between the 2 approaches to exception handling.

  • Try catch block and
  • specifying the candidate exceptions in the throws clause?

Q: When should you use which approach?
Ans: In the first approach as a programmer of the method, you urself are dealing with the exception. This is fine if you are in the best position to decide should be done in case of an exception. Whereas if it is not the responsibility of the method to deal with its exceptions, then do not use this approach. In this case, use the second approach. In the second approach, we are forcing the caller of the method to catch the exceptions, that the method is likely to throw. This is often the approach library creators use. They list the exception in the throws clause, and we must catch them. You will find the same approach throughout the java libraries we use.

Q: Is it necessary that a catch block must follow each try block?
Ans: It is not necessary that a catch block must follow each try block. It should be followed by either a catch block OR a finally block. And whatever exceptions are likely to be thrown should be declared in the throws clause of the method.

Q: If I write return at the end of the try block, will the finally block still execute?
Ans: Yes even if you write return as the last statement in the try block and no exception occurs, the finally block will execute. The finally block will execute and then the control return.

Q: How are the Observer and Observable used?
Ans: Objects that subclass the Observable class maintain a list of observers. When an Observable object is updated, it invokes the update() method of each of its observers to notify the observers that it has changed state. The Observer interface is implemented by objects that observe Observable objects.

Q: What is synchronisation, and why is it important?
Ans: With respect to multithreading, synchronisation is the capability to control
the access of multiple threads to shared resources. Without synchronisation, one thread can modify a shared object while another thread is in the process of using or updating that object’s value. This often leads to significant errors.

Q: How does Java handle integer overflows and underflows?
Ans: It uses those low order bytes of the result that can fit into the size of the type allowed by the operation.

Q: Does garbage collection guarantee that a program will not run out of memory?
Ans: Garbage collection does not guarantee that a program will not run out of memory. Programs can use up memory resources faster than they are garbage collected. It is also possible for programs to create objects that are not subject to garbage collection.

Q: What is the difference between preemptive scheduling and time slicing?
Ans: Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence. Under time slicing, a task executes for a predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors.

Q: When a thread is created and started, what is its initial state?
Ans: A thread is in the ready state after it has been created and started.

Q: What is the purpose of finalisation?
Ans: The purpose of finalisation is to allow an unreachable object to perform any cleanup processing before the object is garbage collected.

Q: What is the Locale class?
Ans: The Locale class is used to tailor program output to the conventions of a particular geographic, political, or cultural region.

Q: What is the difference between a while statement and a do statement?
Ans: A while statement checks at the beginning of a loop to see whether the next loop iteration should occur. A do statement checks at the end of a loop to see whether the next iteration of a loop should occur. The do statement will always execute the body of a loop at least once.

Q: What is the difference between static and nonstatic variables?
Ans: A static variable is associated with the class as a whole rather than with specific instances of a class. Nonstatic variables take on unique values with each object instance.

Q: How is this() and super() used with constructors?
Ans: This() is used to invoke a constructor of the same class. Super () is used to invoke a superclass constructor.

Q: What are synchronised methods and synchronised statements?
Ans: Synchronized methods are methods that are used to control access to an object. A thread only executes a synchronised method after it has acquired the lock for the method’s object or class. Synchronised statements are similar to synchronised methods. A synchronised statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronised statement.

Q: What is daemon thread and which method is used to create the daemon thread?
Ans: Daemon thread is a low priority thread which runs intermittently in the background doing the garbage collection operation for the java runtime system. A setDaemon method is used to create a daemon thread.

Q: What are the steps in the JDBC connection?
Ans: While making a JDBC connection, we go through the following steps :

Step 1: Register the database driver by using :
Class.forName(\” driver class for that specific database\” );

Step 2: Now create a database connection using :
Connection con = DriverManager.getConnection(url,username,password);

Step 3: Now Create a query using :
Statement stmt = Connection.Statement(\” select * from TABLE NAME\”);

Step 4: Execute the query :
stmt.exceuteUpdate();

Q: How does a try statement determine which catch clause should be used to handle an exception?
Ans: When an exception is thrown within the body of a try statement, the catch clauses of the try statement are examined in the order in which they appear. The first catch clause that is capable of handling the exception is executed. The remaining catch clauses are ignored.

If I write System.exit (0); at the end of the try block, will the finally block still execute?
Ans: No, in this case, the finally block will not execute because when you say System.exit (0); the control immediately goes out of the program, and thus finally never executes.

Q: Is Empty .java file a valid source file?
Ans: Yes, an empty .java file is a perfectly valid source file.

Q: Can a .java file contain more than one java classes?
Ans: Yes, a .java file contains more than one java classes, provided at the most one of them is a public class.

Q: Is String a primitive data type in Java?
Ans: No String is not a primitive data type in Java, even though it is one of the most extensively used objects.
Strings in Java are instances of String class defined in java.lang package.

Q: Is the main a keyword in Java?
Ans: No, the main is not a keyword in Java.

Q: Is next to a keyword in Java?
Ans: No, next is not a keyword.

Q: Is delete a keyword in Java?
Ans: No, delete is not a keyword in Java. Java does not make use of explicit destructors the way C++ does.

Q: Is exit a keyword in Java?
Ans: No. To exit a program explicitly, you use exit method in the System object

Q: What happens if you don’t initialise an instance variable of any of the primitive types in Java?
Ans: Java by default, initialises it to the default value for that primitive type. Thus an int will be initialised to 0, and a boolean will be initialised to false.

Q: What will be the initial value of an object reference which is defined as an instance variable?
Ans: The object references are all initialised to null in Java. However, to do anything useful with these references, you must set them to a valid object, else you will get NullPointerExceptions everywhere you try to use such default initialised references.

Q: What are the different scopes for Java variables?
Ans: The scope of a Java variable is determined by the context in which the variable is declared. Thus a java variable can have one of the three scopes at any given point in time.

  • Instance: – These are typical object level variables; they are initialised to default values at the time of the creation of an object. They remain accessible as long as the object is accessible.
  • Local: – These are the variables that are defined within a method. They remain accessible only during method execution. When the method finishes execution, these variables fall out of scope.
  • Static: – These are the class level variables. They are initialised when the class is loaded in JVM for the first time and remain there as long as the class remains loaded. They are not tied to any particular object instance.

Q: What is the default value of the local variables?
Ans: The local variables are not initialised to any default value, neither primitives nor object references. If you try to use these variables without initialising them explicitly, the java compiler will not compile the code. It will complain abt the local variable not being initialised.

Q: How many objects are created in the following piece of code?
MyClass c1, c2, c3;
c1 = new MyClass ();
c3 = new MyClass ();
Ans: Only 2 objects are created, c1 and c3. The reference c2 is only declared and not initialised

Q: Can a public class MyClass be defined in a source file named YourClass.java?
Ans: No the source file name, if it contains a public class, must be the same as the public class name itself with a .java extension.

Q: Can the main method be declared final?
Ans: Yes, the main method can be declared final, in addition to being public static.

Q: What will be the output of the following statement?
System.out.println (“1″ + 3);
Ans: It will print 13.

Q: What will be the default values of all the elements of an array defined as an instance variable?
Ans: If the array is an array of primitive types, then all the elements of the array will be initialised to the default value corresponding to that primitive type. e.g. All the elements of an array of int will be initialised to 0, while that of boolean type will be initialised to false. Whereas if the array is an array of references (of any type), all the elements will be initialised to null.

Java Collection Classes Framework

01-Collection-framework-hierarchy-in-javaArrayList (java.util.ArrayList)

  • extends java.util.AbstractList and implements java.util.List
  • uses the dynamic array to store elements inside ArrayList
  • size increases by 50% of the current array size when ArrayList exceeds its capacity
  • allows inserting/add duplicate elements
  • maintains insertion order
  • accessing elements is faster (as we can use the index to access any elements)
  • manipulation, i.e., delete is very slow due to the shifting of elements
  • ArrayList is non-synchronized

LinkedList (java.util.LinkedList)

  • extends java.util.AbstractList and implements java.util.List & java.util.Deque
  • uses a dynamic array to store elements inside LinkedList
  • allows inserting/add duplicate elements
  • maintains insertion order
  • manipulation, i.e., delete is very faster as no shifting is required (the links break, and a new link is formed while deleting any element from LinkedList)
  • LinkedList is non-synchronized

Vector (java.util.Vector)

  • extends java.util.AbstractList and implements java.util.List & java.util.Deque
  • uses a grow-able array to store elements
  • size increases by 100% of the current array size when Vector exceeds its capacity
  • allows inserting/add duplicate elements
  • maintains insertion order
  • Vector is legacy, and it is synchronized

Difference Between Vector vs. ArrayList

VectorArrayList
Vector is legacy (including other 4 viz., HashTable, Stack, Dictionary, Properties)ArrayList is introduced in Java 1.2
All legacy collection classes are synchronized. Thus Vector is synchronizedArrayList is not synchronized (need to make sure while working in a multi-threaded environment)
Performance-wise vector is slower comparing with ArrayList due to synchronizationThis is comparatively faster as it is non-synchronized
Vector increases its size by 100% of the current array when its capacity exceedsArrayList increases its size by 50% of the current array when its capacity exceeds
Both Iterator & Enumeration can be used to iterate items/elements inside VectorThe only Iterator is allowed to iterate items/elements inside ArrayList

HashSet (java.util.HashSet)

  • extends java.util.AbstractSet and implements java.util.Set
  • uses the hashtable to store elements inside HashSet
  • allows only unique elements (doesn’t allow duplicates, if any duplicate is encountered, then it is overridden)
  • insertion order is not maintained, i.e., items/elements order is random while iterating
  • permits null element
  • HashSet is non-synchronized
  • But it can be easily synchronized using Collections class, i.e., Collections.synchronizedSet(HashSet)
  • HashSet is fail-fast –> throws ConcurrentModificationException is modified by any other means than HashSet’s own remove() method

LinkedHashSet (java.util.LinkedHashSet)

  • extends java.util.HashSet and implements java.util.Set
  • allows only unique elements (doesn’t allow duplicates, if any duplicate is encountered, then it is overridden)
  • allows null element (if more than one is inserted, still it will contain only one null element)
  • insertion order is maintained (in the order they are inserted)

TreeSet (java.util.TreeSet)

  • extends java.util.SortedSet and implements java.util.NavigableSet
  • allows only unique elements (doesn’t allow duplicates, if any duplicate is encountered, then it is overridden)
  • allows null element (if more than one is inserted, still it will contain only one null element)
  • It sorts the elements and maintains ascending order

List vs. Set

  • A list allows duplicate items/elements
  • The set allows only unique items/elements (if the same element inserted again, still it will contain just one element with that value)

PriorityQueue (java.util.PriorityQueue)

  • Maintains FIFO order, i.e., orders in the PriorityQueue are in FIFO fashion
  • FIFO –> First-In-First-Out
  • Important methods of PriorityQueue is poll(), peek(), remove(), head()

HashMap (java.util.HashMap)

  • extends java.util.AbstractMap and implements java.util.Map
  • HashMap stores key\value pairs
  • allows only unique elements
  • maximum of only-one null key is allowed (but it can have any number of null values corresponding to a key)
  • maintains no order
  • HashMap is not synchronized
  • But it can be easily synchronized using Collections class, i.e., Collections.synchronizedMap(hashMap)

LinkedHashMap (java.util.LinkedHashMap)

  • extends java.util.HashMap and implements java.util.Map
  • LinkedHashMap stores key\value pairs
  • allows only unique elements
  • maximum of only-one null key is allowed (but it can have any number of null values corresponding to a key)
  • maintains insertion order (based on Key)
  • LinkedHashMap is not synchronized
  • Note: very similar to HashMap except maintaining insertion order

TreeMap (java.util.TreeMap)

  • extends java.util.AbstractMap and implements java.util.NavigableMap
  • TreeMap stores the key\value pair
  • allows only unique elements
  • The null key is not allowed (but it can have any number of null values corresponding to the key)
  • maintains ascending order (based on Key)
  • TreeMap is not synchronized
  • Note: very similar to LinkedHashMap except maintaining ascending order

Hashtable (java.util.Hashtable)

  • extends java.util.Dictionary and implements java.util.Map
  • HashTable stores key\value pairs
  • allows only unique elements
  • The null key is not allowed, and also null value is not allowed
  • HashTable is synchronized, i.e., thread-safe
  • Doesn’t maintain order (while iterating)

HashTable vs. HasMap

HashTableHashMap
HashTable is legacy (including other 4 viz., Vector, Stack, Dictionary, Properties)HashMap is introduced in Java 1.2
All legacy collection classes are synchronized. Thus HashTable is synchronizedHashMap is not synchronized (need to make sure while working in a multi-threaded environment)
Performance-wise HashTable is slower comparing with HashMap due to synchronizationThis is comparatively faster, as it is non-synchronized
HashTable neither allows null key or null valuesHashMap allows only one null key (although it allows multiple null values corresponding to a key)
Both Iterator & Enumeration can be used to iterate over HashTable items/elementsThe only Iterator is allowed to iterate over HashMap items/elements

Collection Sorting

We should always check 2 important interfaces while dealing with the collection framework in Java. Those are

  1. Comparable
  2. Comparator

Comparable vs Comparator

ComparableComparator
Comparable belongs to the java.lang packageComparator belongs to java.util package
Provides compareTo() method to sort items/elementsSignature: public int compareTo(To);Provides compare() method to sort items/elementsSignature: public int compare(T o1, T o2);
This is used for single-sorting over the collection items/elementsThis is used for multiple-sorting over the collection items/elements
The original class needs to implement java.lang.Comparable interfaces affecting original classA separate new class implements java.lang.Comparator interfaces don’t affect original class
Static method “sort(List)” of Collections class is used to sort collection items/elementsSignature: Collections.sort(List list);Static method “sort(List, Comparator)” of Collections class is used to sort collection items/elementsSignature: Collections.sort(List list, Comparator CMP);

Collection Interview Questions Java

Q) What is Collection in Java?

  • A Collection is a group of element/objects represented as a single unit/entity
  • Programmers can perform various operations like insertion, deletion, sorting, searching, and reversing, etc. on the Collection

Q) What is the Collection framework in Java?

  • A Collection framework consists of various classes & interfaces for the different operational purpose
  • This is introduced in Java 1.2 version after aligning old traditional classes like Vector & Hashtable with new classes like ArrayList & HashSet

Q) Explain the Java Collection framework hierarchy?

01-Collection-framework-hierarchy-in-java

Note: although, Map is listed here it doesn’t fall under Collection umbrella; the only reason to speak Map along with other Collection like List or Set or Queue is that, it also stores a group of key-value pairs and represents a single unit/entity

Q) What are the advantages of the Collection framework in Java?

  • Used to store a group of objects as a single unit/entity
  • Dynamically grow-able in nature, i.e., collection size increases as more number of objects added and size shrinks when deleted
  • Every collection class is based on some standard data structures like for example, the dynamic array for ArrayList & Vector classes and hashtable for HashSet
  • There are standard ready-made API’s available to operate on Collection like adding/deleting elements, etc. which helps to improve the development efforts

Q) Why do we need a Collection framework?

  • The collection is a group of elements stored as a single entity or unit
  • In Java 1.0 version, there are several classes to achieve the above-mentioned concept, but they were all arranged on an ad-hoc basis
  • These classes are Vector, Stack, Dictionary, Hashtable, and Properties
  • These classes are collectively referred to as legacy classes, and every method of legacy classes is synchronized (i.e., Thread-safe access in a multi-threaded environment)
  • With Java 1.2 version introduction, Sun (now Oracle) group came up with Collection framework putting together above legacy classes and newly introduced classes into one place (i.e., java.util package) under the root interface java.util.Collection interface

Collection Class List

Q) List down all classes that implement List interface?

  • ArrayList
  • LinkedList
  • Vector
  • Stack
3-List-interace-in-java

Q) What are the differences between the ArrayList & LinkedList?

  • Operations such as addition, removal or retrieval is very important while discussing the difference between ArrayList & LinkedList
  • For complete differences, read ArrayList v/s LinkedList
ArrayListLinkedList
To store item/elements, ArrayList uses the dynamic array or dynamically re-sizing array, i.e., an internal data structureTo store items/elements, LinkedList uses a doubly-linked list, i.e., an internal data structure
The initial capacity of ArrayList is 10LinkedList doesn’t have any initial capacity, i.e., just constructs an empty list of size 0
When ArrayList exceeds its capacity, then its size increases by 50%No such thing required in LinkedList
When ArrayList exceeds its capacity, then an internally new array is created with 50% more of the original size andOld array data copied into the new arrayNo such overhead, as item/element is added to end of LinkedListDue to this, insertion is faster in LinkedList comparing with ArrayList
Similarly, while deleting from the middle of ArrayList involves a lot of shifting workDeletion is much simpler in LinkedList, as previous and next links get deleted, and a new link is formed

Q) What are the differences between ArrayList & Vector

ArrayListVector
ArrayList is introduced in the original collection framework in Java 1.2 versionVector is a legacy class including Stack, Dictionary, HashTable & Properties and introduced in Java 1.0 version
ArrayList methods are non-synchronizedAll legacy collection classes are synchronized. Thus Vector is synchronized
(i.e., all methods of Vector class is synchronized)
As ArrayList is non-synchronized, hence it isn’t thread-safe. So, the programmer needs to handle thread-safety while working in a multi-threaded environmentAs Vector is synchronized, hence it is thread-safe. So, no need to worry while working in a multi-threaded environment, as only one thread gets the chance to work at any given time

Q) What are the differences between Arrays & ArrayList?

Q) How to obtain an Array from ArrayList in Collection?

  • Use toArrays(); method of Collection interface
  • Read conversion of List to Arrays for complete detail with example
  • Similarly, conversion of Arrays to List is possible, refer above link for example

Q) How to reverse the elements of List items in Collection?

  • Use reverse(); method of Collections class to reverse the elements of Collection items
  • Pass collection items as input arguments, for which items need to be reversed
  • Read How to Reverse the order of elements in ArrayList for complete detail with example

Q) What will happen to List if we add a final keyword to it? Whether more elements can be added to the list?

  • Making any List as final implies that List cannot modify further
  • But it doesn’t stop values to be added to List (use add() or addAll() methods of Collection interface)
  • To restrict any value to be added to the list, then use Collections class’ unmodifiableList(); the method
  • Syntax: Collections.unmodifiableList();

Iterating In Java

Q) What are the different ways to iterate through List?

  • for-loop (regular)
  • Enhanced for-loop
  • Iterating using Iterator of Collection interface
  • Iterating using ListIterator of List interface
  • Iterating List using forEach() in Java 8
  • Read Various ways to iterate through ArrayList – 5 ways

Q) What are the different ways to iterate through Set?

  • Enhanced for-loop (introduced in Java 1.5 version)
  • Iterating using Iterator of Collection interface
  • Iterating Set using forEach() in Java 8
  • Read Various ways to iterate through HashSet – 3 ways

Q) What are the different ways to iterate through Map?

  • Using keySet() method and for-each loop
  • Using the keySet() method and an Iterator interface
  • Using entrySet() method and for-each loop
  • Using entrySet() method and Iterator interface
  • Iterating Map using forEach() in Java 8
  • Read Various ways to iterate through HashMap – 5 ways

Q) What are the differences between Iterator & ListIterator?

  • For complete differences, read Iterator v/s ListIterator
  • Read Iterator in detail for example & explanation
  • Read ListIterator in detail with example & explanation
IteratorListIterator
Iterator interface is applicable for every collection classes like ArrayList, HashSet or HashtableListIterator interface is applicable only for List objects like ArrayList or LinkedList or Vector
Here, we can iterate through collection items only in a FORWARD directionBut with ListIterator, we can iterate through list items either in FORWARD or BACKWARD directions
That is, it is a unidirectional or single-directional cursorThat is, it is a bi-directional cursor

Note: both Iterator & ListIterator introduced in Java 1.2 version as part Collection framework

Q) Why ListIterator introduced, when already Iterator is there to iterate over List items?

  • With Iterator, collection items can be iterated only in a FORWARD direction
  • To iterate in both direction, i.e., FORWARD & BACKWARD, ListIterator is introduced in Java 1.2 version
  • Whereas Iterator is introduced in Java 1.1 version
  • But ListIterator is limited to iterate only on List items

Q) What are the differences between Iterator, ListIterator & Enumeration?

EnumerationIteratorListIterator
This is part of Legacy collection introduced in Java 1.0 versionThis is part of Collection framework introduced in Java 1.2 versionThis is part of Collection framework introduced in Java 1.2 version
Using Enumeration interface, we can enumerate only legacy classes like Hashtable or Vector or PropertiesIterator interface is applicable for every collection classes like ArrayList, HashSet or HashtableListIterator interface is applicable only for List objects like ArrayList or LinkedList or Vector
We can enumerate legacy collection items only in The FORWARD directionHere, too we can iterate through collection items only in the FORWARD directionBut with ListIterator, we can iterate through list items either in forwarding or BACKWARD directions
That is, it is a unidirectional or single-directional cursorThat is, it is a unidirectional or single-directional cursorThat is, it is a ba i-directional cursor

Q) Explain the way to avoid ConcurrentModificationException while iterating Collection items?

  • Generally, ConcurrentModificationException is thrown, if any modification is done while iterating collection items
  • Collection classes introduced in Java 1.2 version like ArrayList or HashSet throws ConcurrentModificationException as it works on original copy leading throwing this exception
  • To avoid this, use concurrent collection classes like CopyOnWriteArrayList, CopyOnWriteArraySet & ConcurrentHashMap introduced in Java 1.5 version as it never throws ConcurrentModificationException
  • Reason: it works on the cloned copy, later which is merged with an original copy by JVM

Q) Which design pattern Iterator follows?

  • Iterator design pattern

Q) What is a fail-safe and fail-fast Iterator in Java?

  • Read CopyOnWriteArrayList for detail with example & explanation
  • Read CopyOnWriteArraySet for detail with example & explanation
  • Read ConcurrentHashMap for detail with example & explanation
Fail-fastFail-safe
While iterating collection items if any modification is done, then ConcurrentModificationException is thrown this is said to be fail-fastWhile iterating collection items if any modification is done and if ConcurrentModificationException is never thrown, then it is said to be fail-safe
Generally, Collection classes introduced in Java 1.2 version like ArrayList or HashSet falls under this categoryNew concurrent classes introduced in Java 1.5 version is fail-safe and never throws ConcurrentModificationException
Here, there is no concept of the cloned copy. Hence, both iteration & modification happening in the same original copy leading to the throwing of ConcurrentModificationExceptionThis is because modification happens in a separate cloned copy & later JVM merges both original with cloned copies
Example: ArrayList, LinkedList, HashSet, TreeSetExample: CopyOnWriteArrayList, CopyOnWriteArraySet, ConcurrentHashMap
Above listed classes comes from java.util packageThe above-listed classes come from java.util.concurrent package

Q) How to iterate over the Map of ArrayList?

  • Get all keys from the Map using the keySet() method
  • Now, iterate over all keys got from Map either using enhanced for-loop or Iterator
  • Using get(“key”); method of Map, get respective ArrayList
  • Again, iterate over ArrayList to get or print all values/element stored in ArrayList
  • For a complete example, read Various ways to iterate over HashMap of ArrayList in Java
  • Also, read Various ways to iterate through ArrayList – 5 ways

Q) How to iterate over the List of HashMap?

  • Iterate through a list (it can be either ArrayList or LinkedList)
  • In each iteration step, one HashMap will be retrieved
  • Get all keys from the Map using the keySet() method
  • Now, iterate over all keys got from Map either using enhanced for-loop or Iterator
  • Using get(“key”); method of Map, get respective values
  • For a complete example, read Various ways to iterate over List of HashMap in Java

Set In Java

Q) What are the differences between List & Set?

ListSet
List stores elements according to insertion order, insertion order is preservedSet stores elements in random order, as it uses hashing technique Insertion order isn’t preserved
While iterating List items, elements will be retrieved as per insertion orderWhile iterating Set items, elements will be retrieved in random order
A list allows duplicate elementsSet doesn’t allow duplicate elements, i.e., it stores only unique elementsNote: if the same element is added again, there won’t be any compile-time or runtime error, just that add() method returns false;
Any number of the NULL object is allowed to add to the ListMaximum of one NULL is allowed

Q) List down all classes that implement the Set interface?

  • HashSet
  • LinkedHashSet
  • TreeSet
14-Set-interace-in-java

Q) Which internal data structure is followed by HashSet?

  • HashSet is backed by a hash table (actually a HashMap instance) to store element/objects

Q) What are the differences between HashSet & TreeSet? And decide which one to use?

  • Read HashSet v/s TreeSet for details with example & explanation
  • Read HashSet in detail with example & explanation
  • Read TreeSet in detail with example & explanation
HashSetTreeSet
Uses the hash table to store element/objects where duplicates are NOT allowedUses the balanced tree to store element/objects where duplicates are NOT allowed
Insertion order is NOT maintained, as it uses the hashing technique to store element/objectsInsertion order is NOT maintained, as element/objects are stored according to some sorting order
HashSet doesn’t deal with sorting order, but it can be converted to TreeSet to store element/objects in some sorting orderTreeSet ts = new TreeSet(HashSet);Element/objects stored in TreeSet are according to some sorting order; it could be either default natural sorting order or programmer-defined customized sorting order
While iterating HashSet, we will get items in random orderWhile iterating TreeSet, we will get items in sorted order; either natural ordering or customized sorting order

Q) Explain NavigableSet & its advantages?

  • NavigableSet interface is a sub-interface of SortedSet interface (i.e.; NavigableSet extends SortedSet)
  • To represent a group of element/objects as a single unit/entity, where duplicates aren’t allowed, and element/objects are stored according to some sorting order
  • It allows only unique element/objects to be inserted
  • It stores element/objects in sorting order
  • NavigableSet interface defines more specific methods for navigation purposes, in addition to inherited methods from Set/SortedSet/Collection interfaces
  • This is introduced in Java 1.6 version for navigation support
19-NavigableSet-interace-in-java
19-NavigableSet-interace-in-java

Q) How many null elements can be added to Set, i.e., HashSet or TreeSet?

  • As Set maintains uniqueness w.r.t elements added to the set, i.e., either HashSet or TreeSet
  • Maximum of only one null element can be added to any Set implemented classes
  • Even if 2nd null is added to set, it won’t throw any error (compile-time or runtime)
  • Actually, an earlier null element will be replaced by the new null element
  • Read HashSet in detail with example & explanation
  • Read TreeSet in detail with example & explanation

Q) In which Java version, LinkedHashSet is introduced?

  • LinkedHashSet is an implementation class of Set interface (i.e.; LinkedHashSet implements Set)
  • This is introduced in Java 1.4 version
  • LinkedHashSet uses the combination of LinkedList & hash table to store element/objects

Queue In Java

Q) What are the difference between peek(), poll() & remove() methods of Queue interface ?

  • Read Queue interface in detail for example & explanation
  • Similarly, read PriorityQueue which is the Queue implemented class
Queue methodsDescription
Object peek();retrieve head element without removing from Queue returns null if Queue is empty
Object poll();retrieve & remove the head element from Queue returns null if the Queue is empty
Object remove();retrieve & remove the head element from Queue

Q) List down all classes that implement the Queue interface?

  • PriorityQueue
  • PriorityBlockingQueue (through BlockingQueue interface)
  • LinkedBlockingQueue (through BlockingQueue interface)

Map In Java

Q) List down all classes that implement Map interface?

  • HashMap
  • LinkedHashMap
  • WeakHashMap
  • IdentityHashMap
  • TreeMap (through SoretdMap –> NavigableMap)
  • Hashtable
  • Properties (through Hashtable)
025-Map-interace-in-java

Q) What are the different ways to get Collection views for Map interface?

Map methodsDescription
Set keySet();returns set of keys from invoking map this provides collection/set views of Map
Collection values();returns collection containing the values of invoking map this provides collection/set views of Map
Set entrySet():returns set of map entries of type Map. Entry this provides collection/set views of Map
  • Read the keySet() method for getting all keys from the Map
  • Read values() method for getting all values from Map
  • Read entrySet() method for getting all entries from Map, in the form of key-value pairs

Q) In which Java version, LinkedHashMap is introduced?

  • LinkedHashMap is an implementation class of Map interface (i.e.; LinkedHashMap implements Map)
  • This is introduced in Java 1.4 version
  • LinkedHashMap uses the combination of LinkedList & hash table to store Map entries (i.e.; key-value pairs)
28-LinkedHashMap-in-java

Q) Explain IdentityHashMap in detail?

  • IdentityHashMap is exactly the same as that of HashMap with few differences
  • HashMap: JVM uses equals() method to check uniqueness of keys before storing
  • IdentityHashMap: JVM uses == operator to check uniqueness of keys before storing
30-IdentityHashMap-in-java

Q) Explain WeakHashMap in detail?

  • WeakHashMap is exactly the same as that of HashMap with few differences
  • HashMap: If objects don’t have any reference outside of HashMap, even then objects aren’t eligible for Garbage Collection. HashMap has precedence over Garbage Collector
  • WeakHashMap: If objects don’t have any reference outside of WeakHashMap, still JVM executes Garbage collection. The garbage collector has precedence over objects inside WeakHashMap. Kind of stores only weak references
31-WeakHashMap-in-java
31-WeakHashMap-in-java

Q) Explain NavigableMap & its advantages?

  • NavigableMap interface is a sub-interface of SortedMap interface (i.e.; NavigableMap extends SortedMap)
  • To represent a group of key-value pairs as a single unit/entity, where duplicates keys aren’t allowed and keys are stored according to some sorting order
  • It allows only unique keys to be inserted
  • Stores key-value pairs in sorting order on the basis of keys only, not values
  • NavigableMap interface defines more specific methods for navigation purposes, in addition to inherited methods from Map/SortedMap interfaces
  • This is introduced in Java 1.6 version for navigation support to TreeMap
33-NavigableMap-interace-in-java
33-NavigableMap-interace-in-java

Q) How Map is different from List & Set?

  • List & Set interface extends Collection interface, which stores a group of objects as a single entity
  • Whereas Map stores a group of key-value pairs as a single entity
  • Note: Map interface doesn’t extend Collection interface

Q) What are the differences between Map & Set?

  • Set stores group of objects as a single entity and duplicate objects aren’t allowed
  • Map stores group of key-value pairs as a single entity where keys are unique but values can be duplicate

Q) What are the differences between HashMap & HashSet?

  • Read HashMap v/s HashSet for details with example & explanation
HashMapHashSet
HashMap implements Map interfaceHashSet implements Set interface
Used to store key-value pairs using put method example: hm.put(key, value);Used to store only unique objects using add method example: hs.add(object);
HashMap doesn’t allow duplicate keys but values can be duplicatedHashSet doesn’t allow duplicate objects
HashMap allows a maximum of one null key but any number of NULL values allowedHashSet allows a maximum of one null object to be added
HashMap internally uses an array of Entry<K, V> objectsHashSet internally uses HashMap to store unique objects
Performance-wise, HashMap is faster than HashSetPerformance-wise, HashSet is slower than HashMap

Q) What are the differences between HashMap & Hashtable?

HashMapHashtable
HashMap is introduced in collection framework in Java 1.2 versionHashtable is a legacy class and introduced in Java 1.0 version
HashMap is NOT synchronizedHashtable is synchronized
All methods of HashMap is NOT synchronized i.e.; it is not thread-safeAll methods of HashMap is synchronized i.e.; thread-safe
Multiple threads are allowed to accessOnly one thread is allowed access; other threads have to wait to get access, after obtaining lock/monitor
Performance-wise, this is relatively high comparing with Hashtable, as there is no wait timePerformance-wise, this is relatively slow due to synchronized methods as there is only one thread allowed to access, at any given point of time
NULL insertion allowed for both keys and valuesNULL insertion is not allowed for both keys and values
Maximum of one NULL key and there is no upper limit for valuesSimply, not allowed for both keys & values

Q) What are the differences between HashMap & TreeMap? And decide which one to use?

HashMapTreeMap
Uses the hash table to store key-value pairs (i.e.; map entries) where duplicate keys are NOT allowedUses the Red-Black tree to store key-value pairs (i.e.; map entries) where duplicate keys are NOT allowed
Insertion order is NOT maintained, as it uses a hashing technique to store key-value pairs (i.e.; map entries)Insertion order is NOT maintained, as key-value pairs (i.e.; map entries) are stored according to some sorting order
HashMap doesn’t deal with sorting order; but it can be converted to TreeMap to store key-value pairs (i.e.; map entries) in some sorting orderTreeMap ts = new TreeMap(hashMap);Keys in TreeMap are sorted, according to some sorting order; it could be either default natural sorting order or programmer-defined customized sorting order
While iterating HashMap, we will get items in random orderWhile iterating TreeMap, we will get items in sorted order; either natural ordering or customized sorting order
This is introduced in the original collection framework in Java 1.2 versionThis is also introduced in the original collection framework in Java 1.2 version
Key: Allows NULL insertion but a maximum of only one NULL value: No upper limit for NULL values against any unique keyKey: From Java 1.7 version, NULL is not allowed to insert; But with Java version less than 1.6, only as 1st element allowed (for keys)Value: No upper limit for NULL values against any unique key

Q) What are the differences between HashMap & ConcurrentHashMap?

HashMapConcurrentHashMap
HashMap is not synchronizedConcurrentHashMap is synchronized
In a multi-threaded environment, HashMap is faster than ConcurrentHashMap as multiple threads can operateHence, performance is high as there is no need to acquire the ockAs it is synchronized, the lock needs to be acquired before operating, although for certain portion of the MapHence, performance is relatively low when comparing with HashMap
NULL insertion is possible for the key but a maximum of one null key and any number of null values against any keyNULL insertion isn’t allowed for both keys and values
While one thread iterating HashMap items, if any other thread tries to modify Map items then ConcurrentModificationException is thrownWhile one thread iterating ConcurrentHashMap items, other thread are happily can modify Map items and it never throws ConcurrentModificationException
That’s it is a fail-fast iteratorThat’s it is a fail-safe iterator
This is introduced in the original collection framework in Java 1.2 versionThis is introduced in Java 1.5 version
We can convert this Map item into the synchronized map by using the Collections class utility method but still, only one thread is allowed to operate on a Map objectThere is no such need here, as it is already thread-safe and multiple threads can operate after acquiring bucket-level or segment-level locking strategies

Q) What are the differences between Comparator & Comparable?

Comparable interfaceComparator interface
Present in java.lang packagePresent in java.util package
Defines only one important method
i.e.;public int compareTo(Object obj);
Defines 2 method
i.e.;public int compare(Object obj1, Object obj2); public boolean equals(Object object);
It is basically used for default natural sorting order [DNSO]This is preferred for customized sorting order [CSO]
This interface needs to be implemented in the same class for which sorting is requiredA separate class is required to implement Comparator interface
Elements of List can be sorted using comparable interface example: Collection.sort(listItems);Elements of List can be sorted using comparator interface example: Collection.sort(listItems, comparator);
String & wrapper classes’ like Integer, Double, etc implement comparable interfaceThere are very few classes’ which implements Comparator interface

Q) What are the differences between Collection & Collections?

  • Collection interface is a root of Collection framework hierarchy
  • List, Set & Queue interfaces extend Collection interface
  • Collections (with extras appending at the end) is a utility class for operating on Collection items
  • An operation such as sorting, searching, shuffling, reversing, swapping, synchronizing, etc can be performed on collection items using Collections class’ methods
  • Read Collection interface for details with example & explanation
  • Read Collections class for details with example & explanation

Q) Which Collection classes are thread-safe or synchronized?

  • By default, all legacy classes introduced in Java 1.0 version are synchronized namely Vector, Hashtable, Stack, Properties, Dictionary
  • And newly introduced concurrent classes in Java 1.5 version are synchronized namely ConcurrentHashMap, CopyOnWriteArrayList, CopyOnWriteArraySet

Q) How to convert any un-synchronized collection classes into synchronized Collection class?

  • To convert any un-synchronized collection class to synchronize, use synchronized collection() method from Collections class
  • But we also have, special conversion methods for List, Set or Map i.e.; synchronizedList(), synchronizedSet(), synchronizedMap()
  • Examples:
Collection collection = null;
List list = null;
Set set = null;
Map map = null;
 
 
// to convert any collection class to synchronized Collection
Collections.synchronizedCollection(collection);
 
// to convert List class to synchronized List
Collections.synchronizedList(list);
 
// to convert Set class to synchronized Set
Collections.synchronizedSet(set);
 
// to convert Map class to synchronized Map
Collections.synchronizedMap(map);

Q) What are the ways to make or restricts any collection to read-only?

  • To restricts any collection to read-only, then use the unmodifiable collection() from Collections class
  • Example:
// to restrict collection class to read-only
Collections.unmodifiableCollection(collection);

Q) What are Ordered and Sorted Collection classes in the Java Collection framework?

  • Ordered Collection –> ArrayList, LinkedList, Vector, LinkedHashSet, LinkedHashMap
  • Sorted Collection –> TreeSet & TreeMap
  • Un-ordered Collection –> HashSet & HashMap

Q) Does enumeration interface considered legacy ?

  • Yes, Enumeration interface is legacy
  • It is introduced in Java 1.0 version
  • Apart from Enumeration interface, below-mentioned classes are considered as Legacy collection
  • Hashtable, Vector, Stack, & Properties classes and Dictionary abstract class

Java 5 Concurrent Collection

Q) List down all classes introduced in Java 5 Concurrent Collection?

  • ConcurrentHashMap
  • CopyOnWriteArrayList
  • CopyOnWriteArraySet

Q) What is ConcurrentHashMap in Java ?

  • ConcurrentHashMap is the implementation class of ConcurrentMap interface (i.e.; ConcurrentHashMap implements ConcurrentMap)
  • ConcurrentHashMap uses a hash table data structure to store key-value pairs (which is known as map entry)
  • Allows only unique keys and there is no such restriction on values
  • NULL insertion isn’t allowed for both key and values
  • Allows concurrent access to reading and update operations (i.e.; 2 or more threads can operate on the same ConcurrentHashMap object simultaneously)
  • For the read operation, the lock isn’t required
  • But for an update operation, the lock is required but that’s only for part of the Map object (i.e.; Bucket level locking)
  • Actually, the bucket is divided into n-number of parts and one lock is associated with each part
  • These locks are referred to as concurrency-level
  • ConcurrentHashMap never throws ConcurrentModificationException while 2 or more threads operating simultaneously

Q) What is CopyOnWriteArrayList ?

  • CopyOnWriteArrayList is the implementation class of List interface (i.e.; CopyOnWriteArrayList implements List)
  • For every modify or update operation, a new separate cloned copy is created and modification is performed on the cloned copy; while other threads can iterate over an original copy
  • After modification or updating, JVM takes care of merging both the copies (i.e.; original and cloned copy) –> so that we get the latest copy with all updation or modification
  • Since every time a new separate cloned copy is created for updating or modification. Therefore, it is suited for the multi-threaded environment where there are more number of reading/get operation and comparatively less update/modify operation
  • While one thread iterating over the original copy, other threads can modify with the separate cloned copy and compiler won’t throw any ConcurrentModificationException; which isn’t case with ArrayList
  • It never throws ConcurrentModificationException while 2 or more threads operating simultaneously i.e.; it is a fail-safe iterator
  • But, there are a certain limitation too with CopyOnWriteArrayList which isn’t cased with ArrayList like, while iteratingCopyOnWriteArrayList, remove operation isn’t possible and compiler throws UnsupportedOperationException
  • Other than above-discussed points, all other properties of ArrayList are applicable for CopyOnWriteArrayList too

Q) What is CopyOnWriteArraySet ?

  • CopyOnWriteArraySet is the implementation class of Set interface (i.e.; CopyOnWriteArraySet implements Set)
  • Internally COWAS is implemented using COWAL
  • So for every modify or update operation, a new separate cloned copy is created and modification is performed on the cloned copy; while other threads can iterate over an original copy
  • After modification or updation, JVM takes care of merging both the copies (i.e.; original and cloned copy) à so that we get the latest copy with all updation or modification
  • Since every time a new separate cloned copy is created for updation or modification. Therefore, it is suited for the multi-threaded environment where there are more read/get operation and comparatively less update/modify operation
  • While one thread iterating over the original copy, other threads can modify with the separate cloned copy and compiler won’t throw any ConcurrentModificationException; which isn’t case with other Set implemented classes like HashSet or TreeSet
  • It never throws ConcurrentModificationException while 2 or more threads operating simultaneously i.e.; it is a fail-safe iterator
  • But, there are a certain limitation too with CopyOnWriteArraySet which isn’t cased with Set implemented classes like HashSet or TreeSet like while iterating COWAS, remove operation isn’t possible and compiler throws UnsupportedOperationException

Q) Explain difference between ArrayList & CopyOnWriteArrayList ?

CopyOnWriteArrayListArrayList
CopyOnWriteArrayList is synchronized or newly introduced thread-safe classArrayList is not synchronized
For every update operation, a new separate cloned copy is created and there is a memory & merging overhead for JVMHence, performance is relatively low when comparing with ArrayListIn a multi-threaded environment, ArrayList is faster than CopyOnWriteArrayList as multiple threads can operateHence, performance is high as there is no need to acquire the lock
While one thread iterating CopyOnWriteArrayList items, other threads happily can modify, as it works on separately cloned copy and it never throws ConcurrentModificationExceptionWhile one thread iterating ArrayList items, if any other thread tries to modify the same ArrayList object then ConcurrentModificationException is thrown
That’s it is a fail-safe iteratorThat’s it is a fail-fast iterator
An iterator of CopyOnWriteArrayList can perform read operation safely; while iterating through COWAL items but as soon as, remove operation is performed, the compiler throws UnsupportedOperationExceptionAn iterator of ArrayList can perform both read and remove operations; while iterating through

Q) Difference between Synchronized Collection & Concurrent Collection?

Concurrent CollectionSynchronized Collection
Concurrent Collection are newly introduced thread-safe class (i.e.; synchronized)This is a thread-safe version of Collection class
Multiple threads are allowed to operate on Concurrent Collection, as it works on a separate cloned copy for update/modify operationsOnly one thread is allowed to operate on a synchronized collection, by locking over complete list object
While one thread iterating Concurrent Collection object, other threads happily can modify, as it works on separately cloned copy and it never throws ConcurrentModificationExceptionWhile one thread iterating on a synchronized collection object, if any other threads try to modify the same object then ConcurrentModificationException is thrown
That’s it is a fail-safe iteratorThat’s it is a fail-fast iterator
There is no such restriction while iterating on Concurrent CollectionWe can safely iterate outside the synchronized blockWhile iterating synchronized Collection, make sure to iterate inside the synchronized block; Otherwise, we may face non-deterministic behavior
An iterator of Concurrent Collection can perform read operation safely; while iteratingBut as soon as, remove operation is performed, the compiler throws UnsupportedOperationExceptionAn iterator of a synchronized collection can perform both read and remove operations; while iterating

Avatar for Softwaretestingo Editorial Board

I love open-source technologies and am very passionate about software development. I like to share my knowledge with others, especially on technology that's why I have given all the examples as simple as possible to understand for beginners. All the code posted on my blog is developed, compiled, and tested in my development environment. If you find any mistakes or bugs, Please drop an email to softwaretestingo.com@gmail.com, or You can join me on Linkedin.

Leave a Comment