Explore topic-wise InterviewSolutions in .

This section includes InterviewSolutions, each offering curated multiple-choice questions to sharpen your knowledge and support exam preparation. Choose a topic below to get started.

1.

How can you make an ArrayList read-only in Java?

Answer»

With the help of Collections.unmodifiableList() method, we can easily make an ArrayList read-only.  This function takes a CHANGEABLE ArrayList as an input and returns the ArrayList's read-only, unmodified view.

Example:

import java.util.*; public class InterviewBit { public static void MAIN(String[] args) throws Exception { try { // creating object of ArrayList<String> LIST<String> sample_list = new ArrayList<String>(); sample_list.add(“practice”); sample_list.add(“SOLVE”); sample_list.add(“interview”); // DISPLAYING the initial list System.out.println("The initial list is : " + sample_list); // using unmodifiableList() method List<String> read_only_list = Collections .unmodifiableList(sample_list); // displaying the read-only list System.out.println("The ReadOnly ArrayList is : " + read_only_list); // Trying to add an element to the read-only list System.out.println("Trying to modify the ReadOnly ArrayList."); read_only_list.add(“job”); } catch (UnsupportedOperationException e) { System.out.println("The exception thrown is : " + e); } }}

Output:

The initial list is : [practice, solve, interview]The ReadOnly ArrayList is : [practice, solve, interview]Trying to modify th eReadOnly ArrayList.Exception thrown : java.lang.UnsupportedOperationException

We can see that as we try to add an element to a read-only ArrayList we get an exception thrown.

2.

Differentiate between Array and ArrayList in Java.

Answer»

Following are the differences between Arrays and ArrayLists in Java :

  • Java provides arrays as a fundamental functionality. ArrayList is a component of Java's collection system. As a RESULT, It is used to ACCESS array members, while ArrayList provides a set of methods for accessing and modifying components.
  • ArrayList is not a fixed-size data structure, but Array is. When creating an ArrayList OBJECT, there is no need to provide its size. Even if we set a maximum CAPACITY, we can add more parts afterward.
  • Arrays can include both primitive data types and class objects, depending on the array's definition. ArrayList, on the other hand, only accepts object entries and not primitive data types. Note that when we use arraylist.add(1);, the primitive int data type is converted to an Integer object.
  • Members of ArrayList are always referencing to objects at various memory locations since ArrayList can't be constructed for primitive data types  As a result, the actual objects in an ArrayList are never kept in the same place. The references to the REAL items are maintained in close proximity. Whether an array is primitive or an object depends on the type of the array. Actual values for primitive kinds are continuous regions, whereas allocation for objects is equivalent to ArrayList.
  • Many other operations, such as indexOf() and delete(), are supported by Java ArrayList. Arrays do not support these functions.
3.

What is the default size of the load factor in hashing based collection?

Answer»

The DEFAULT LOAD factor size is 0.75. The default capacity is CALCULATED by MULTIPLYING the initial capacity by the load factor.

4.

Differentiate between HashSet and HashMap.

Answer»

HashSet is a Set Interface implementation that does not allow duplicate values. The essential point is that objects STORED in HashSet must override equals() and HASHCODE() methods to ensure that no duplicate values are stored in our set.

HASHMAP is a Map Interface implementation that maps a key to a value. In a map, duplicate keys are not permitted.

HashSetHashMap
It implements the Set Interface.It implements the Map Interface.
It does not allow duplicate values.The key needs to be unique while two different keys can have the same value.
While adding an element it requires only one object as a parameter.While adding an entry, it requires two object values, the Key and the Value as the parameter.
Internally, HashSet uses HashMap to add entries. The key K in a HashSet is the argument supplied in the add(Object) method. For each value supplied in the add(Object) method, Java assigns a dummy value.There is no CONCEPT of duplicate values.
It is slower than HashMap.It is faster than HashSet.
It uses the add() method for adding elements.It uses the put() method for adding data elements.
5.

Differentiate between Set and Map in Java.

Answer»

The Set interface is provided by the Java.util package. The set interface is established by extending the COLLECTION interface. We can't add the same element to it since it won't let US. Because it contains elements in a sorted order, it does not keep the insertion order. The Set interface in Java is used to build the MATHEMATICAL Set.

Map is SIMILAR to Set in that it is used to store a collection of objects as a single entity. A KEY-value pair is used to store each object. Because each value is associated with a unique key, we can quickly obtain the value using just the key.

SetMap
It cannot have values that are repeated. It is not possible to add the same elements to a set. Only the unique value is stored in each class that implements the Set interface.It is possible for different keys to have the same value. The map has a unique key and values that are repeated. 
Using the keyset() and entryset() methods, we can quickly iterate the Set items.It is not possible to iterate across map elements. To iterate the elements, we must convert Map to Set.
The Set interface does not keep track of insertion order. Some of its classes, such as LinkedHashSet, however, keep the insertion order. The Map does not keep track of the insertion sequence. Some Map classes, such as TreeMap and LinkedHashMap, do the same thing.
6.

What are some of the best practices while using Java Collections?

Answer»

Following are some of the best practices while using Java Collections : 

  • Selecting the appropriate Collection:
    Before we use a collection, we must choose the most relevant collection for the problem we are seeking to SOLVE. If we pick the wrong one, our program MAY still run, but it will be inefficient. On the other hand, if we pick the right one, our solution will be a lot simpler and our program will run much faster.
  • Specifying the initial capacity of the Collection :
    Almost all collection classes contain an OVERLOADED constructor that determines the collection's initial capacity. That is, if we know exactly how many pieces will be added to the collection, we can define the initial capacity when establishing a new instance.
  • Using isEmpty() instead of size():
    To check if a collection is empty or not we should use the isEmpty() method rather than finding the size of the collection and comparing it with zero. This enhances the readability of the code.
  • Using Iterators for iterating over the collections:
    We should use iterators for traversing over the collection elements instead of using a for loop for the same. The reason is that the iterator may throw ConcurrentModificationException if any other thread tries to modify the collection after the iterator has been created. This saves us from bugs.
  • Using Concurrent Collections over synchronized wrappers:
    Instead of UTILIZING the synchronized collections generated by the Collections.synchronizedXXX() methods, we should consider using concurrent collections from the java.util.concurrent package in multi-threaded applications. Because concurrent collections employ various synchronization strategies such as copy-on-write, compare-and-swap, and specific LOCKS, they are designed to give maximum performance in concurrent applications.
  • Eliminating Unchecked warnings:
    We should not disregard unchecked warnings from the Java compiler. The ideal practice is to get rid of any warnings that aren't checked.
  • Favoring Generic types:
    We should build new methods with generic parameters in mind, and convert existing methods to use type parameters, just as we should with generic types because generic methods are safer and easier to use than non-generic ones. Generic methods also aid in the creation of APIs that are both general and reusable.
7.

What is a priority queue in Java?

Answer»

When the objects are MEANT to be processed in order of priority, a PriorityQueue is used. A Queue is known to follow the First-In-First-Out method, however, there are occasions when the components of the queue must be handled in order of priority, which is where the PriorityQueue comes into PLAY. The priority HEAP is the foundation of the PriorityQueue. The members of the priority queue are ORDERED according to NATURAL ordering or by a Comparator provided at queue construction time.

Serializable, Iterable<E>, Collection<E>, Queue<E> interfaces are implemented by the PriorityQueue class in Java.

8.

Can you add a null element into a TreeSet or HashSet?

Answer»

We can add NULL ELEMENTS in a HASHSET but we cannot add null elements in a TreeSet. The reason is that TreeSet uses the compareTo() method for comparing and it throws a NullPointerException when it ENCOUNTERS a null ELEMENT.

9.

Differentiate between HashSet and TreeSet. When would you prefer TreeSet to HashSet?

Answer»

Following are the differences between HashSet and TreeSet:-

  • Internal implementation and speed
    • HashSet: For search, insert, and remove operations, it takes constant time on average. TreeSet is slower than HashSet. A hash table is used to implement HashSet.
    • TreeSet: For search, insert, and delete, TreeSet takes O(Log N), which is higher than HashSet. TreeSet, on the other hand, PRESERVES ordered data. Higher() (Returns the least higher element), floor(), CEILING(), and other operations are also supported. In TreeSet, these operations are likewise O(Log n), and HashSet does not implement them. A Self-Balancing Binary Search Tree is used to implement TreeSet (Red Black Tree). In Java, TreeSet is backed by TreeMap.
  • Way of storing elements 
    The elements of a HashSet are not ordered. In Java, the TreeSet class keeps objects in a Sorted order defined by the Comparable or Comparator methods. By default, TreeSet components are sorted in ascending order. It has a number of methods for dealing with ordered sets, including FIRST(), last(), headSet(), tailSet(), and so on.
  • Allowing Null values 
    Null objects are allowed in HashSet. TreeSet does not allow null objects and throws a NULLPOINTEREXCEPTION. This is because TreeSet compares keys using the compareTo() method, which throws java.lang. NullPointerException.
  • Comparison
    HashSet compares two objects in a Set and detects duplicates using the equals() method. For the same purpose, TreeSet employs the compareTo() method. If equals() and compareTo() are not consistent, that is, if equals() returns true for two equal objects but compareTo() returns zero, the contract of the Set interface will be broken, allowing duplicates in Set implementations like TreeSet.

Following are the cases when TreeSet is preferred to HashSet :

  1. Instead of unique elements, sorted unique elements are required. TreeSet returns a sorted list that is always in ascending order.
  2. The locality of TreeSet is higher than that of HashSet. If two entries are close in order, TreeSet places them in the same data structure and hence in memory, but HashSet scatters the entries over memory regardless of the keys to which they are linked.
  3. To sort the components, TreeSet employs the Red-Black tree method. TreeSet is a fantastic solution if you need to do read/write operations regularly.
10.

Differentiate between Iterator and ListIterator in Java.

Answer»

In Java's Collection framework, iterators are used to obtain elements one by one. It can be used on any TYPE of Collection object. We can execute both read and remove operations using Iterator. Iterator MUST be used whenever we want to iterate elements in all Collection framework implemented interfaces, such as Set, List, Queue, and Deque, as well as all Map interface implemented classes. The only cursor accessible for the entire collection framework is the iterator.

ListIterator is only useful for classes that implement List collections, such as array lists and linked lists. It can iterate in both directions. When we WISH to enumerate List elements, we must use ListIterator. This cursor has additional methods and capabilities than the iterator.

IteratorListIterator
Only has the ability to traverse components in a Collection in a forward direction.In both forward and backward orientations, can traverse components in a Collection.
Iterators cannot be used to obtain INDEXES.It offers methods to get element indexes at any time while traversing List, such as next Index() and previous Index().
It aids in the traversal of Maps, Lists, and Sets.Only List may be traversed, not the other two.
It throws a Concurrent Modification Exception since it can't add elements.At any time, you can quickly add elements to a collection.
next(), remove(), and has Next are some of the Iterator's functions ().next(), previous(), has Next(), has Previous(), and add() are some of the List Iterator's methods
11.

Differentiate between List and Set in Java.

Answer»

The LIST interface is used to keep track of an ordered collection. It is the Collection's child interface. It is an ordered collection of objects that allows for the storage of DUPLICATE values. The insertion order is preserved in a list, which enables positional access and ELEMENT insertion. 

The set interface is PART of java.util package and extends the Collection interface. It is an unordered collection of objects in which duplicate values cannot be stored. It's an interface for using the mathematical set. This interface inherits the Collection interface's METHODS and adds a feature that prevents duplicate elements from being inserted.

SetList
It is an unordered sequence.It is an ordered sequence.
Duplicate elements are not permitted in Set.Duplicate elements are allowed in the list
Access to items from a certain position is not permitted.Elements can be accessed based on their position.
A null element can only be stored once.It is possible to store several null elements.
12.

Differentiate between ArrayList and Vector in java.

Answer»

Following are the differences between ArrayList and Vector in java :

  • Vector is synchronized, which means that only one thread can access the code at a time, however, ArrayList is not synchronized, which means that multiple threads can operate on ArrayList at the same time. In a multithreading system, for example, if one thread is executing an add operation, another thread can be performing a removal action. 
    If multiple threads access ArrayList at the same time, we must either synchronize the code that UPDATES the list fundamentally or enable simple ELEMENT alterations. The addition or deletion of element(s) from the list is referred to as structural change. It is not a structural change to change the value of an existing element.
  • Data Growth: Both ArrayList and Vector dynamically expand and SHRINK to make the most use of storage space, but the manner they do it is different. If the number of elements in an array exceeds its limit, ArrayList increments 50% of the current array size, while vector increments 100%, thereby doubling the current array size.
  • Performance: ArrayList is faster than vector operations because it is non-synchronized, but vector operations are slower since they are synchronized (thread-safe). When one thread WORKS on a vector, it acquires a lock on it, requiring any other threads WORKING on it to wait until the lock is released.
  • Vector can traverse over its elements using both Enumeration and Iterator, whereas ArrayList can only traverse using Iterator.
13.

Difference between ArrayList and LinkedList.

Answer»
ArrayListLinkedList
The elements of this class are STORED in a dynamic array. This class now supports the storage of all types of objects thanks to the addition of generics.The elements of this class are stored in a doubly-linked list. This class, like the ArrayList, allows for the storage of any type of object.
The List interface is implemented by this class. As a result, this SERVES as a list.The List and Deque interfaces are both implemented by this class. As a result, it can be used as both a list and a deque.
Because of the internal implementation, manipulating an ArrayList takes LONGER. Internally, the array is scanned and the memory bits are shifted whenever we remove an element.Because there is no concept of changing memory bits in a doubly-linked list, manipulating it takes less time than manipulating an ArrayList. The reference link is changed after traversing the list.
This class is more useful when the application requires DATA storage and access.This class is more useful when the application requires data manipulation.
14.

Explain the various interfaces used in the Collection framework.

Answer»

The collection framework has several interfaces, each of which is used to store a different sort of data. The interfaces included in the framework are listed below.

1. Iterable Interface: This is the collection framework's primary interface. The iterable interface is extended by the collection interface. As a result, all interfaces and classes implement this interface by default. This interface's main purpose is to provide an iterator for the collections. As a result, this interface only has one abstract method, the iterator. 

2. Collection Interface: The collection framework's classes implement this interface, which extends the iterable interface. This interface covers all of the basic methods that every collection has, such as adding data to the collection, removing data from the collection, clearing data, and so on. All of these methods are incorporated in this interface because they are used by all classes, regardless of their implementation style. Furthermore, including these methods in this interface guarantees that the method names are consistent across all collections. In summary, we may conclude that this interface LAYS the groundwork for the implementation of collection classes.

3. List Interface: The collection interface has a child interface called the list interface. This interface is devoted to list data, in which we can store all of the objects in an ordered collection. This also allows for the presence of redundant data. Various classes, such as ArrayList, Vector, Stack, and others, implement this list interface. We can create a list object with any of these classes because they all implement the list.

4. Queue Interface: A queue interface, as the name implies, follows the FIFO (First In First Out) order of a real-world queue line. This interface is for storing all elements in which the order of the elements is important. When we try to shop at a store, for example, the bills are issued on a first-come, first-served basis. As a result, the INDIVIDUAL whose request is first in line receives the bill first. PriorityQueue, DEQUE, ArrayDeque, and other classes are available. Because all of these subclasses implement the queue, we can use any of them to create a queue object.

5. Deque Interface: It differs slightly from the queue data structure.  Deque, also known as a double-ended queue, is a data structure in which elements can be added and removed from both ends. The queue interface is extended by this interface. ArrayDeque is the class that implements this interface. Because this class implements the deque, we can use it to create a deque object.

6. Set Interface: A set is an unordered group of objects in which duplicate values cannot be kept. This collection is utilised when we want to avoid duplication of things and only keep the ones that are unique. Various classes, such as HASHSET, TREESET, LinkedHashSet, and others, implement this set interface. We can create a set object with any of these classes because they all implement the set.

7. Sorted Set Interface: This interface resembles the set interface in appearance. The only difference is that this interface provides additional methods for maintaining element ordering. The sorted set interface is an extension of the set interface that is used to manage sorted data. TreeSet is the class that implements this interface. We can create a SortedSet object using this class because it implements the SortedSet interface.

15.

What are the advantages of the Collection framework?

Answer»

FOLLOWING are the advantages of the Collection framework:-

Consistent API: The API has a core set of interfaces like Collection, Set, List, or Map, and all the classes (ARRAYLIST, LinkedList, Vector, and so on) that implement these interfaces have some common set of methods.

Cuts programming effort: Instead of worrying about the Collection's design, a programmer may concentrate on how BEST to USE it in his program. As a result, the fundamental principle of Object-oriented programming (i.e. abstraction) has been applied successfully.

Improves program speed and quality by offering high-performance implementations of useful data STRUCTURES and algorithms, as the programmer does not have to worry about the optimum implementation of a certain data structure in this scenario. They can simply use the best implementation to improve the performance of their program significantly.

16.

Explain the hierarchy of the Collection framework in Java.

Answer»

The entire collection FRAMEWORK hierarchy is MADE up of FOUR fundamental INTERFACES: Collection, List, Set, Map, and two specific interfaces for SORTING called SortedSet and SortedMap. The java.util package contains all of the collection framework's interfaces and classes. The following diagram depicts the Java collection structure.

Here, e denotes extends, i denotes implements

  • Extends: The keyword extends is used to create inheritance between two classes and two interfaces.
  • Implements: The keyword implements are used to create inheritance across classes and interfaces.
17.

Differentiate between Collection and collections in the context of Java.

Answer»

Collection : In the JAVA.util.package, there is an interface called a collection. It's USED to represent a collection of separate objects as a single entity. It's equivalent to the container in the C++ programming language. The collection framework's root interface is referred to as the collection. It has a number of classes and interfaces for representing a collection of individual objects as a single unit. The key sub-interfaces of the collection interface are List, Set, and Queue. Although the map interface is part of the Java collection framework, it does not inherit the interface's collection. The Collection interface's most significant functions are add(), remove(), clear(), size(), and CONTAINS().

Collections: The java.util.package has a utility class called Collections. It defines various utility methods for working with collections, such as sorting and searching. All of the methods are static. These techniques give developers much-needed convenience, allowing them to INTERACT with Collection Framework more successfully. It provides methods like sort() to sort the collection elements in the normal sorting order, and min() and max() to get the minimum and maximum value in the collection elements, respectively.

CollectionCollections
It's used to represent a collection of separate objects as a single entity.It defines a number of useful methods for working with collections.
It is an interface.It is a utility class.
Since Java 8, the Collection is an interface with a static function. Abstract and default methods can also be found in the Interface.It only has static methods in it.
18.

What is the difference between Array and Collection in java?

Answer»

Array and Collection are equivalent in terms of STORING object references and manipulating data, but they differ in a number of ways. The following are the primary distinctions between an array and a Collection:

ArrayCollection
Arrays have a SET size, which means that once we build one, we can't change it to meet our needs.Collection are naturally grow-able and can be customized to meet our needs. We can change its size as per our requirement.
When it comes to performance, Arrays are the preferred to Collection.Considering performance, Collection are not preferred to Arrays.
Only homogeneous data type elements can be stored in arrays.Both homogeneous and heterogeneous components can be stored in a collection.
Because arrays have no underlying data STRUCTURE, there is no ready-made METHOD support.Any collection class is built on a standard data structure, and so there is ready-made method support for every demand as a performance. These methods can be used directly, and we are not RESPONSIBLE for their implementation.
Objects and primitives can both be stored in arrays.Only object types can be stored in a collection.
When it comes to memory, Arrays are not preferred to Collection.Considering memory, Collection are preferred to Arrays.