Tricky Java Interview Questions for 5 Years Experience

In this post, we will share the Tricky Java Interview Questions for 5 Years Experience. Our content is well researched and collected from the employee who have cleared the Java interview.

1. How would you implement a Singleton Design Pattern in Java?

2. How is the thread lifecycle maintained using the ExecutorService Framework?

The ExecutorService framework is used to manage and control the lifecycle of the thread

Below are the 3 key concepts is important to maintain the life cycle of threads

  • ExecutorService: This is an Interface that manages a pool of threads for executing tasks
  • ThreadPoolExecutor: core implementation of Executor service
  • Task Queue: A queue where tasks are stored
Management of Thread Life Cycle:
  1. Creation of ExecutorService: we create an ExecutorService instance using one of the factory methods provided by the Executors class, such as newFixedThreadPool, newCachedThreadPool, or newSingleThreadExecutor.
  2. Submission of Tasks: we submit tasks to the ExecutorService for execution. and Tasks can be submitted either as Runnable instances or Callable instances. The ExecutorService manages the execution of these tasks asynchronously.
  3. Task Execution: The ExecutorService executes tasks using the threads from its managed thread pool. Depending on the type of ExecutorService (fixed thread pool, cached thread pool, etc.), it may reuse threads or create new ones as needed.
  4. Completion of Tasks: As tasks are executed, they can be completed successfully, throw exceptions, or be canceled. The ExecutorService handles the completion of tasks and manages their results or exceptions.
  5. Shutdown: When we are done using the ExecutorService, we should shut it down explicitly by calling its shutdown() method.

3. How to make class immutable?

There are 5 principles we have to follow to make any class immutable

  • Make the class final or sealed: This prevents subclasses from being created, ensuring the class definition and as we know final class can’t be inherit
  • Make field private and final: This restricts direct access and modification of internal data.
  • No setter methods: Instead, provide getter methods to access data, but return copies of mutable objects if applicable.
  • Perform deep copies in constructors and methods: When dealing with mutable objects within the class, create copies to avoid modifying the original data.
  • Consider immutability libraries: Some languages offer libraries or built-in mechanisms to simplify creating immutable classes.

4. What is the purpose of the finalize method? Is it guaranteed to be called?

finalize is a method that is defined in the Object class and can be overridden by the subclasses. The finalize method in java is called by the garbage collector before an object is garbage collected. This method can be used to perform any necessary cleanup before the object is destroyed, such as releasing resources or closing connections. However, it’s important to note that the garbage collector is not guaranteed to call the finalize method in java and Java Virtual Machine (JVM) decides when to run the garbage collector, and the timing of garbage collection is not predictable.

5. What is the difference between HashMap and HashTable?

HashMap and HashTable are both implementations of the Map interface in Java. Lets understand the difference between them.


Aspect
HashMapHashTable
Synchronizationit is not synchronized and not thread-safe. It means if multiple threads access a HashMap concurrently, it must be synchronized externallyit is synchronized and thread-safe, ensuring that only one thread can access the Hashtable at a time. This makes it suitable to use in multithreaded environments
Null Keys and Valuesallows one null key and any number of null valuesneither keys nor values can be null. If you try to insert a null key or value then NullPointerException will be thrown
Which one to use and whenrecommended for new code due to its better performance and the fact that it allows null values.use of HashTable is limited due to its synchronization nature. In modern era HashMap or ConcurrentHashMap are often preferred
Performance
give higher performance as it is not synchronizedit gives slower performance as it is synchronized
Iterating Over ElementsHashMap Iterator is fail-fastHashTable iterator is fail safe

6. What if we don’t override equal and HashCode?

Consider, we have to store Student Objects as a key in HashMap and Student class does  not override equals() and HashCode().

In this case, all the student object (keys) will be considered duplicate even if they have same content and it end up getting stored in different buckets.

7. What if we override equal but not HashCode?

Consider, we have to store Student Objects as a key in HashMap and Student class does override equals() but not HashCode().

In this case, all the student object (keys) will be considered duplicate even if they have same content and it end up getting stored in different buckets.

8. What if we override hashCode but not equals()?

Consider, we have to store Student Objects as a key in HashMap and Student class does override hashCode() but not equals().

In this case, all the student object (keys) will be considered duplicate even if they have same content . Student object having same content will be stored in same bucket but in a separate Node(Collision).

9. What if we override hashCode and equals() both?

Consider, we have to store Student Objects as a key in HashMap and Student class does override both the methods().

In this case, student object having same content will generate same HashCode and it gives the same index number. While storing the key-value pair on bucket, if their is already a node present then equals return true and value gets update of that key.

10.What is Fail Fast and Fail Safe iterator?

Fail fast iterators are the iterators which can quickly detect any modifications made to the underlying collection while the iterator is iterating and immediately throws ‘’ConcurrentModificationException’. It ensures that the collection will not be modified by other threads during iteration. These iterators works on main memory area and mostly use in collections like ArrayList, HashMap, and other standard Java Collections.

Advantages: It detect concurrent modifications quickly which helps to avoid unpredictable behaviour and ensures that issues are identified early during development.

For Example:

Fail safe iterators make a copy of the collections at the time of creation. It does not throw any exception even if we do any modification while the iterator is iterating. These iterators are mostly use in ConcurrentHashMap and CopyOnWriteArrayList.

Advantages: Fail safe Iterators continues to work even if the underlying collection is modified which ensures the stability of the system. However, it might not reflect the most recent changes in the collection updated by other Threads.

For example:

The choice between fail-fast and fail-safe iterators depends on the specific requirements of your application. Fail-fast iterators are generally preferred when quick detection of concurrent modifications is crucial, whereas fail-safe iterators are suitable when you need to avoid exceptions during iteration and can tolerate working with a snapshot of the collection.

11.Can you explain internal working of HashMap?

The HashMap class is part of the Java Collections Framework and is used to store key-value pairs. It works on the principle of hashing and it provide constant time complexity when we perform put and get operations on it.

Lets understand the internal workings of HashMap:

  1. When you create a HashMap, array of 16 buckets is created in the memory to store key-value pairs.
  2. When you put a key-value pair into the HashMap, the hash of key is used to determine the bucket where the pair will be stored. There are several steps to be performed internally.

Lets understand with an example:

  1. Create a HashMap with an initial capacity of 16 (by default)
  1. Put key-value pairs into the HashMap
  1. Calculate the HashCode of key ”oneKey”. Here, the hash of the key is computed using the hashCode() method of the key object.
  2. The generated hash code is used to calculate the index of the bucket in which the key-value pair will be stored.
  3. Calculate index as hash & (capacity – 1), where hash is the generated hash code, and capacity is the current capacity of the HashMap(by default 16)., lets say index is 4
  4. Once the index is calculated, it then checks whether the specific bucket is empty or not.
  5. Go to index 4 of array, create a node and place this pair if there is no node exist
  6. If there is already a node exist at particular index then compare the content of existing key with given key using equals() method
  7. If both keys are equal then override the value
  8. If both are different then create another node and place given key-value pair.

To handle collisions, HashMap uses a linked list (a chain) at each bucket. If multiple key-value pairs map to the same bucket, they are stored as nodes in this linked list.

Process to retrieve values:

When you retrieve values using keys, the same process is repeated to calculate the bucket index, locate the correct node in the linked list and get the value.

12.When Resizing gets happen in HashMap?

If you keep on adding the key-value pair in HashMap, if the load factor (the ratio of the number of elements to the capacity) exceeds a threshold, the HashMap is resized, and the existing elements of array are rehashed into a larger array of buckets.

13.What is Load Factor in HashMap?

The load factor of a HashMap is the ratio of the number of stored elements to the total number of buckets.

It is denoted by size/capacity.

The default load factor in Java is 0.75.

14.What is Collision in HashMap?

Collision occur in HashMap when different generate the same hash code which end up placing the key-value pair  to the same index/bucket

HashMap uses a linked list (chain of nodes) at each bucket to handle collisions. In short, each bucket can store multiple key-value pairs in a linked list. When a new key-value pair gets stored to an existing bucket, it is added as a new node in the linked list.

15.What is equal and HashCode contract?

The contract between the equals() and hashCode() methods is important when working with Hash implementation like HashMap. We have to override hashCode(0 method if we are overriding equals() method. If we don’t override any one of them, it might give incorrect result while working with HashMap. 

This contract says that if two object are equal as per equals(0 method, then their hashcode() should return same integer value.

For example:

If x.equals(y) returns true, then x.hashCode() should be equal to y.hashCode().

Note: There might be the scenario where two unequal object will have the same hashCode and this problem known as Collision.

16.What if we don’t override equal and HashCode?

Consider, we have to store Student Objects as a key in HashMap and Student class does  not override equals() and HashCode().

In this case, all the student object (keys) will be considered duplicate even if they have same content and it end up getting stored in different buckets.

17.What if we override equal but not HashCode?

Consider, we have to store Student Objects as a key in HashMap and Student class does override equals() but not HashCode().

In this case, all the student object (keys) will be considered duplicate even if they have same content and it end up getting stored in different buckets.

18.What if we override hashCode but not equals()?

Consider, we have to store Student Objects as a key in HashMap and Student class does override hashCode() but not equals().

In this case, all the student object (keys) will be considered duplicate even if they have same content . Student object having same content will be stored in same bucket but in a separate Node(Collision).

19.What if we override hashCode and equals() both?

Consider, we have to store Student Objects as a key in HashMap and Student class does override both the methods().

In this case, student object having same content will generate same HashCode and it gives the same index number. While storing the key-value pair on bucket, if their is already a node present then equals return true and value gets update of that key.

20.What changes has been made in HashMap in java 8?

There are several enhancements and improvements were introduced to the HashMap class.

If a bucket contains large number of collision keys then all the entries will get stored in Balanced tree instead of linked list once the threshold is reached.

While converting list to binary tree, hashCode() method is used as a differentiator, If there are same hash code value present in same bucket then the bigger one will go to the right of the tree and smaller one will go on the left side. However, if the hash code is same then comparable interface comes into the picture that will compare the keys and find the key position to be placed in a tree to maintain the proper order.

Advantage: It helps us to achieve high performance.

21.Why we need lambda expression and what benefit we get in terms of memory management?

Lambda expression is the most important features of Java 8. It helps us to write concise, compact and readable code in a. Functional style.

Earlier, we used to provide implementation of Functional Interface in a separate class which is very difficult to maintain and it also create a separate .class file in memory. We also used to provide implementation in anonymous class in which class it needed but it is not reusable, as we can’t access those implementation outside class. To overcome this problem, Lambda function or expression comes into the picture.

Lets understand with an example:

22.How to remove duplicate elements from a list using stream API?

You can use Stream.distinct() method to remove duplicate elements. This method is just like distinct clause in SQL which eliminate the duplicate entry.

23.How to remove duplicate elements from a list using standard Java Collections?

You can use HashSet to remove duplicate elements as it only contains unique elements.

Drawback of this approach is that it does not maintain the insertion order after removing duplicate elements. However, if you have to maintain the insertion order then go with LinkedHashSet.

24.Find the sum of all the elements present in a list using Stream API?

You can use Stream.reduce() to get the sum of all the elements.

There is one more way to achieve sum by using mapToInt() method provided by Stream Api which convert our stream to an IntStream Object.

25. What is the purpose of the ‘Comparator’ interface in Java? How is it different from the ‘Comparable’ interface?

Comparable and Comparator are very useful for sorting the collection of objects but they serve different purpose and are used in different contexts.

ComparableComparator
Comparable Interface provides compareTo() method to sort objectsComparator Interface provides compare() method to sort objects
Comparable is used for natural or default ordering where we know the sorting requirement at design phase only.Comparator is used for custom ordering and we can provide n number of implementation in different java classes.
Comparable modifies the class that implements itComparator doesn’t modify any class

Comparable interface compareTo(Object o) method need to be implemented and it should be implemented in such a way that it returns -1 if the current object is less than the specified object and returns zero if they are equal and +1 if the current object is greater than the specified one. 
Comparator interface compare(Object o1, Object o2) method need to be implemented and it should be implemented in such a way that it returns -1 if the first argument is less than the second and returns zero if they are equal and +1 if the first argument is greater than the second.

26. What is double checked locking with Singleton?

The double checked pattern is used to avoid obtaining the lock every time the code is executed. If the call are not happening together then the first condition will fail and the code execution will not execute the locking thus saving resources.

  1. If an instance was already created, don’t do anything – avoid locking threads
  2. The first thread that has acquired the lock checks and sees that there is no such object and creates it. It releases the lock and the second one can do the same – it has to check if the object exists because the first one may have created it.

So basically the outer if is used to prevent redundant locks – it lets all thread know that there is already an object and they don’t need to lock/do anything. And the inner if is used to let a concurrent thread know whether another has already created the object or not.

27. What is String Literal Pool ?

The String Literal Pool is special kind of memory area in Java Heap Memory where string literals gets stored. In Java, when you create a String literal using double quotes (” “), the JVM checks if the String already exists in the pool. If it does, the reference to the existing String object is returned. If not, a new String object is created in the pool, and its reference is returned.

Leave a comment