Top 20 Java Interview Questions for Experienced Developers

Preparing for Java Interviews to get a Job on Investment banks? here is a list of 20+ core Java questions with answers

javinpaul
Javarevisited
19 min readNov 17, 2019

--

There are a lot of Java developers trying for Java development roles on Investment banks like Barclays, Credit Suisse, Citibank, etc.; still, many of them don’t have any idea of what kind of questions they can expect there.

In this article, I’ll share a couple of frequently asked questions from investment banks to Java developer of more than three years of experience.

Yes, these questions are not for freshers or 1 to 2 years of Java experienced professional as often banks don’t hire them via open interviews; they mostly join as graduate trainees.

It’s not guaranteed that you will get these questions;, most likely, you won’t, but this will give you enough idea of what kind of questions you can expect. BTW, the more you prepare, the better your preparation will be.

Btw, if you think 21 is not enough and you need more than check out these additional 40 Java questions for the telephonic interview and these 200+ Java questions from the last five years as well. If you like to read books, you can also check Grokking the Java Interview book and Grokking the Spring Boot Interview where I have shared many such questions and you can even use friends20 code to get 20% discount now.

Once you have done those, you would be more confident to given any Java interview, be it a phone interview or face-to-face.

Anyway, without wasting any more of your time, let’s dive into some of the standard Java interview questions from banks, which I have collected from some of my friends and colleagues who appeared on interviews of these banks.

And, if you are not a Medium member then I highly recommend you to join Medium and read great stories like this from great authors on different field. You can join Medium here

20+ Java Interview Questions With Answers

Without wasting any more of your time, here is my list of some of the frequently asked core Java interview questions from interviews.

Question 1: What’s wrong using HashMap in the multi-threaded environment? When get() method go to the infinite loop? (answer)

Answer: Well, nothing is wrong; it depends upon how you use. For example, if you initialize a HashMap by just one thread and then all threads are only reading from it, then it’s perfectly fine.

One example of this is a Map that contains configuration properties.

The real problem starts when at least one of that thread is updating HashMap, i.e. adding, changing, or removing any key-value pair.

Since put() operation can cause re-sizing and which can further lead to an infinite loop, that’s why either you should use Hashtable or ConcurrentHashMap, later is even better.

Question 2. Does not overriding hashCode() method has any performance implication? (answer)

This is a good question and opens to all, as per my knowledge, a poor hash code function will result in the frequent collision in HashMap which eventually increases the time for adding an object into Hash Map.

From Java 8 onwards though collision will not impact performance as much as it does in earlier versions because after a threshold the linked list will be replaced by a binary tree, which will give you O(logN) performance in the worst case as compared to O(n) of a linked list.

Question 3: Does all property of the Immutable Object needs to be final in Java? (answer)

Not necessary, as stated in the linked answer article, you can achieve the same functionality by making a member as non-final but private and not modifying them except in constructor.

Don’t provide a setter method for them, and if it is a mutable object, then don’t ever leak any reference for that member.

Remember making a reference variable final, only ensures that it will not be reassigned a different value. However, you can still change the individual properties of an object, pointed by that reference variable.

This is one of the critical points; the Interviewer likes to hear from candidates. If you want to know more about final variables in Java, I recommend joining The Complete Java MasterClass on Udemy, one of the best, hands-on courses.

Question 4: How does substring () inside String works? (answer)

Another good Java interview question, I think the answer is not sufficient, but here it is, “Substring creates a new object out of source string by taking a portion of the original string.”

This question was mainly asked to see if the developer is familiar with the risk of memory leak, which sub-string can create.

Until Java 1.7, substring holds the reference of the original character array, which means even a sub-string of 5 characters extended, can prevent 1GB character array from garbage collection, by containing a strong reference.

This issue was fixed in Java 1.7, where the original character array is not referenced anymore, but that change also made the creation of substring a bit costly in terms of time. Earlier it was on the range of O(1), which could be O(n) in the worst case of Java 7 onwards.

Btw, if you want to learn more about memory management in Java, I recommend to check out Understanding the Java Virtual Machine: Memory Management course by Kevin Jones on Pluralsight.

By the way, you would need a Pluralsight membership to join this course, which costs around $29 per month or $299 per year (14% discount). If you don’t have this plan, I highly recommend joining as it boosts your learning and as a programmer, you always need to learn new things.

Alternatively, you can also use their 10-day-free-trial to watch this course for FREE.

Question 5: Can you write a critical section code for the singleton? (answer)

This core Java question is another common question and expecting the candidate to write Java singleton using double-checked locking.

Remember to use a volatile variable to make Singleton thread-safe.

Here is the code for a critical section of a thread-safe Singleton pattern using double-checked locking idiom:

public class Singleton {private static volatile Singleton _instance;/** * Double checked locking code on Singleton 
* @return Singelton instance
*/public static Singleton getInstance() {if (_instance == null) {synchronized (Singleton.class) {if (_instance == null) {_instance = new Singleton();}}}return _instance; }}

On the same note, it’s good to know about classical design patterns likes Singleton, Factory, Decorator, etc. If you are interested in this, then this Design Pattern library is an excellent collection of that.

Question 6: How do you handle error conditions while writing a stored procedure or accessing the stored procedure from java? (answer)

This is one of the tough Java interview questions, and again it’s open for you all; my friend didn’t know the answer, so he didn’t mind telling me.

My take is that a stored procedure should return an error code if some operation fails, but if stored procedure itself fails, then catching SQLException is the only choice.

The Effective Java 3rd Edition also has some good advice on dealing with errors and exceptions in Java, which is worth reading.

Question 7 : What is difference between Executor.submit() and Executer.execute() method ? (answer)

This Java interview question is from my list of Top 50 Java multi-threading question answers; It’s getting popular day by day because of the huge demand of a Java developer with good concurrency skills.

This Java interview question answers that former returns an object of Future which can be used to find the result from a worker thread)

There is a difference when looking at exception handling. If your tasks throw an exception and if it was submitted with executing this exception, will go to the uncaught exception handler (when you don’t have provided one explicitly, the default one will just print the stack trace to System.err).

If you submitted the task with submit() the method any thrown exception, checked exception or not, is the part of the task’s return status.

For a task that was submitted with submitting and that terminates with an exception, the Future.get() will re-throw this exception, wrapped in an ExecutionException.

If you want to learn more about Future, Callable, and Asynchronous computing and take your Java Concurrency skills to the next level, I suggest you check out Java Concurrency Practice in Bundle course by Java Champion Heinz Kabutz.

It’s an advanced course, which is based upon the classic Java Concurrency Practice book by none other than Brian Goetz, which is considered as a bible for Java Developers. The course is definitely worth your time and money. Since Concurrency is a robust and tricky topic, a combination of this book and class is the best way to learn it.

Question 8: What is the difference between factory and abstract factory pattern? (answer)

Answer: Abstract Factory provides one more level of abstraction. Consider different factories each extended from an Abstract Factory and responsible for the creation of different hierarchies of objects based on the type of factory. E.g., AbstractFactory extended by AutomobileFactory, UserFactory, RoleFactory, etc. Each factory would be responsible for the creation of objects in that genre.

If you want to learn more about the Abstract Factory design pattern, then I suggest you check out the Design Pattern in Java course, which provides excellent, real-world examples to understand patterns better.

Here is the UML diagram of the factory and abstract factory pattern:

If you need more choices, then you can also check out my list of Top 5 Java Design Pattern courses.

Question 9: What is Singleton? is it better to make the whole method synchronized or only critical section synchronized? (answer)
Singleton in Java is a class with just one instance in the entire Java application, for example, java.lang.Runtime is a Singleton class.

Creating Singleton was tricky before Java 4, but once Java 5 introduced Enum, it’s straightforward.

You can see my article How to create thread-safe Singleton in Java for more details on writing Singleton using the enum and double-checked locking, which is the purpose of this Java interview question.

Question 10: Can you write code for iterating over HashMap in Java 4 and Java 5? (answer)
Tricky one, but he managed to write using a while and a for a loop. There are four ways to iterate over any Map in Java; one involves using essential Set() and iterating over a key and then using get() method to retrieve values, which is a bit expensive.

The second method involves using entrySet() and iterating over them either by applying for each loop or while with Iterator.hasNext() method.

This one is a better approach because both key and value object is available to you during Iteration, and you don’t need to call get() method for retrieving the value, which could give the O(n) performance in case of a huge linked list at one bucket.

You can further, see my post four ways to iterate over Map in Java for detailed explanation and code examples.

Question 11 : When do you override hashCode() and equals()? (answer)

Whenever necessary, especially if you want to do an equality check based upon business logic rather than object equality, e.g. two employee objects are equal if they have the same, even though they are two different objects created by a different part of the code.

Also, overriding both these methods is a must if you want to use them as key in HashMap.

Now, as part of the equals-hashcode contract in Java, when you override equals, you must override hashcode as well; otherwise, your object will not break invariant of classes, e.g. Set, Map which relies on equals() method for functioning correctly.

You can also check my post five tips on equals in Java to understand the subtle issue which can arise while dealing with these two methods.

Question 12: What will be the problem if you don’t override hashCode() method? (answer)
If you don’t replace the equals method, then the contract between equals and hashcode will not work, according to which two objects which are equal by equals() must have the same hashcode.

In this case, another object may return different hashCode and will be stored on that location, which breaks invariant of HashMap class because they are not supposed to allow duplicate keys.

When you add the object using the put() method, it iterates through all Map.Entry objects present in that bucket location, and update the value of the previous mapping if Map already contains that key. This will not work if the hashcode is not overridden.

If you want to learn more about the role of equals() and hashCode() in Java Collections like Map and Set, I suggest you go through Java Fundamentals: Collections course on Pluralsight by Richard Warburton

Question 13 : Is it better to synchronize critical section of getInstance() method or whole getInstance() method? (answer)
The answer is an only critical section because if we lock the whole method that every time someone calls this method, it will have to wait even though we are not creating an object.

In other words, synchronization is only needed when you create an object, which happens only once.

Once an object has created, there is no need for any synchronization. That’s very poor coding in terms of performance, as synchronized methods reduce production up to 10 to 20 times.

Here is the UML diagram of the Singleton design pattern:

By the way, there are several ways to create a thread-safe singleton in Java, including Enum, which you can also mention as part of this question or any follow-up.

If you want to learn more, you can also check to Learn Creational Design Patterns in Java — A #FREE Course from Udemy.

Question 14: Where does equals() and hashCode() method comes in the picture during the get() operation on HashMap? (answer)

This core Java interview question is a follow-up of previous Java question, and the candidate should know that once you mention hashCode, people are most likely ask, how they are used in HashMap.

When you provide a crucial object, first it’s hashcode method is called to calculate bucket location. Since a bucket may contain more than one entry as a linked list, each of those Map.Entry an object is evaluated by using equals() method to see if they contain the crucial actual object or not.

I strongly suggest you read my post, How HashMap works in Java, another tale of an interview to learn more about this topic.

Questions 15: How do you avoid deadlock in Java? (answer)

If you know, a deadlock occurs when two threads try to access two resources which are held by each other, but to that happen the following four conditions need to match:

  1. Mutual exclusion
    At least one process must be held in a non-sharable mode.
  2. Hold and Wait
    There must be a process holding one resource and waiting for another.
  3. No preemption
    resources cannot be preempted.
  4. Circular Wait
    There must exist a set of processes

You can avoid deadlock by breaking the circular wait condition. To do that, you can make arrangements in the code to impose the ordering on the acquisition and release of locks.

If lock were acquired in a logical order and released in just opposite order, there would not be a situation where one thread is holding a lock that is received by others and vice-versa.

You can further see my post, how to avoid deadlock in Java for the code example, and a more detailed explanation.

I also recommend, Applying Concurrency and Multi-threading to Common Java Patterns By José Paumard on Pluralsight for a better understanding of concurrency patterns for Java developers.

Question 16: What is the difference between creating String as new() and literal? (answer)

When we create a String object in Java with a new() Operator, it’s built-in a heap and not added into the string pool while String created using literal are created in the String pool itself, which exists in the PermGen area of heap.

String str = new String(“Test”)

Does not put the object str in the String pool, we need to call String. Intern () method, which is used to put them into the String pool explicitly.

It’s only when you create a String object as String literal e.g. String s = “Test” Java automatically puts that into the String pool.

By the way, there is a catch here Since we are passing arguments as “Test,” which is a string literal, it will also create another object as “Test” on the string pool.

This is the one point, which has gone unnoticed until knowledgeable readers of the Javarevisited blog suggested it. To learn more about the difference between a String literal and String object, see this article.

Here is a beautiful image which shows this difference quite well:

Question 17: What is Immutable Object? Can you write Immutable Class? (answer)

Immutable classes are Java classes whose objects cannot be modified once created. Any modification in an Immutable object results in a new purpose; for example, String is immutable in Java.

Mostly Immutable classes are also final in Java to prevent subclasses from overriding methods, which can compromise Immutability.

You can achieve the same functionality by making member as non-final but private and not modifying them except in constructor.

Apart from obvious, you also need to make sure that you should not expose the internals of an Immutable object, mainly if it contains a mutable member.

Similarly, when you accept the value for the mutable member from client e.g. java.util.Date, use the clone() method to keep a separate copy for yourself to prevent the risk of malicious client modifying mutable reference after setting it.

The Same precaution needs to be taken while returning value for a mutable member, return another separate copy to the client, never return original reference held by Immutable class. You can also see my post How to create an Immutable class in Java for step by step guide and code examples.

Question 18: Give the simplest way to find out the time a method takes for execution without using any profiling tool? (answer)

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 plan for execution.

Remember that if the time taken for execution is too small, it might show that it is taking zero milliseconds for performance. Try it on a method which is big enough, in a sense the one which is doing a considerable amount of processing

Question 19: Which two ways you need to implement to use any Object as key in HashMap? (answer)

To use any object as Key in HashMap or Hashtable, it must implement equals and hashcode method in Java.

You can also read How HashMap works in Java for a detailed explanation of how the equals and hashcode method is used to put and get an object from HashMap.

Question 20: How would you prevent a client from directly instantiating your concrete classes? For example, you have a Cache interface and two implementation classes MemoryCache and DiskCache. How do you ensure there is no object of these two classes created by the client using new() keyword.
I leave this question for you to practice and think about before I answer. I am sure you can figure out the right way to do this, as this is one of the critical decisions to keep control of classes in your hand, great from a maintenance perspective.

A lot of you asked me to answer this question, so I am answering it now.

In Java, one way to prevent clients from directly instantiating your concrete classes is by using the factory method pattern. The factory method pattern involves defining an interface or an abstract class for creating objects, and allowing subclasses or implementing classes to alter the type of objects that will be created.

Here’s how you could structure your classes to achieve this:

// Cache interface
public interface Cache {
void storeData(String key, String data);
String retrieveData(String key);
}

// MemoryCache implementation
public class MemoryCache implements Cache {
// Private constructor to prevent direct instantiation
private MemoryCache() {}

// Factory method to create an instance of MemoryCache
public static MemoryCache createMemoryCache() {
return new MemoryCache();
}

// Implement the Cache interface methods
@Override
public void storeData(String key, String data) {
// Implementation for storing data in memory
}

@Override
public String retrieveData(String key) {
// Implementation for retrieving data from memory
return null;
}
}

// DiskCache implementation
public class DiskCache implements Cache {
// Private constructor to prevent direct instantiation
private DiskCache() {}

// Factory method to create an instance of DiskCache
public static DiskCache createDiskCache() {
return new DiskCache();
}

// Implement the Cache interface methods
@Override
public void storeData(String key, String data) {
// Implementation for storing data on disk
}

@Override
public String retrieveData(String key) {
// Implementation for retrieving data from disk
return null;
}
}

In this example, the constructors of MemoryCache and DiskCache are made private, making it impossible for clients to directly instantiate them using the new keyword. Instead, clients should use the provided factory methods (createMemoryCache and createDiskCache) to obtain instances of these classes.

By following this approach, you provide a controlled way for clients to obtain instances of your classes while maintaining encapsulation and preventing direct instantiation.

21. Designing a Connection Pool

Imagine you are tasked with designing a connection pool for a database access library. The library will be used by multiple clients in a high-performance system. Each client might need to perform various read and write operations on the database.

How would you design a connection pool that meets the following requirements:

  1. Efficiently manages a pool of database connections.
  2. Supports concurrent usage by multiple clients without causing contention or bottlenecks.
  3. Provides a mechanism for handling connection timeouts and failures gracefully.
  4. Ensures that connections are reused effectively to reduce overhead.

Discuss the key components, design patterns, and considerations you would take into account to implement such a connection pool. How would you handle connection acquisition, release, and monitoring?

Answer: Designing a connection pool is a complex task that involves considerations for efficiency, concurrency, fault tolerance, and resource management. Here’s an overview of how you might approach designing a connection pool:

Key Components:

  1. Connection Pool Class:
  • Create a central class responsible for managing the connection pool.
  • Implement a singleton pattern to ensure a single instance throughout the application.
  1. Connection Object:
  • Define a connection object representing a connection to the database.
  • Include properties like connection status, creation time, last usage time, etc.
  1. Connection Pool Configuration:
  • Allow configuration of parameters such as maximum pool size, minimum pool size, timeout settings, etc.
  • Use a configuration mechanism (properties, XML, etc.) to make the pool adaptable to different environments.

Design Patterns and Strategies:

  1. Object Pool Pattern:
  • Implement the Object Pool pattern to manage a pool of connection objects efficiently.
  • Pre-create a pool of connections during initialization to minimize runtime overhead.
  1. Concurrency Control:
  • Use thread-safe data structures and synchronization mechanisms to handle concurrent access.
  • Implement techniques like connection leasing and reference counting to control access.
  1. Timeout Handling:
  • Implement a mechanism to handle connection timeouts.
  • Regularly check and evict idle connections beyond a specified timeout period.
  1. Connection Reuse:
  • Implement connection reuse to minimize the overhead of opening and closing connections.
  • Use an algorithm to allocate and release connections efficiently.

Connection Acquisition and Release:

  1. Connection Acquisition:
  • When a client requests a connection, check if there are available connections in the pool.
  • If the pool is not full, create a new connection; otherwise, wait or return an error based on the configured behavior.
  1. Connection Release:
  • When a client is done using a connection, return it to the pool for reuse.
  • Reset the connection state and update relevant metadata (last usage time).

Monitoring and Fault Tolerance:

  1. Monitoring:
  • Implement monitoring features to log and track the usage of connections.
  • Log information about connection acquisition, release, timeouts, and failures.
  1. Fault Tolerance:
  • Implement mechanisms to handle database connection failures.
  • Consider implementing connection validation to ensure that a connection is still valid before it is provided to a client.

Additional Considerations:

  1. Idle Connection Cleanup:
  • Periodically check for idle connections and remove them from the pool to free up resources.
  1. Graceful Shutdown:
  • Implement a graceful shutdown mechanism to release all connections when the application exits.
  1. Dynamic Pool Sizing:
  • Consider dynamically adjusting the pool size based on demand to optimize resource utilization.
  1. Connection Pool Statistics:
  • Provide APIs for clients to retrieve statistics about the connection pool, such as the number of active connections, total connections, etc.

By carefully considering these components, design patterns, and strategies, you can create a robust and efficient connection pool that meets the requirements of a high-performance system. Keep in mind that the specific implementation details may vary based on the programming language and database technology being used.

Further Learning

  1. Grokking the Java Interview book
  2. The Complete Java Masterclass
  3. Java Fundamentals: The Java Language
  4. Core Java SE for the Impatient
  5. 200+ Java Interview questions
  6. Grokking the Spring Boot Interview

Closing Notes

Great!!, you made it to the end of the article… Good luck with your Java Programming Interview! It’s certainly not going to be easy, but by following these questions, you are one step closer to accomplishing your goal.

Please consider following me (javinpaul) on Medium if you’d like to be notified of my new post, and don’t forget to follow me on Twitter!

Other Java Articles You May Like to Explore
The Complete Java Developer RoadMap
10 Things Java and Web Developer Should Learn in depth
10 Testing Tools Java Developers Should Know
5 Frameworks Java Developers Should Learn in depth
5 Courses to Learn Big Data and Apache Spark in Java
10 Trails to learn DevOps for Java Developers
10 Books Every Java Programmer Should Read
10 Tools Java Developers uses in their day-to-day work
10 Tips to become a better Java Developer

And, if you are not a Medium member then I highly recommend you to join Medium and read great stories like this from great authors on different field. You can join Medium here

--

--

javinpaul
Javarevisited

I am Java programmer, blogger, working on Java, J2EE, UNIX, FIX Protocol. I share Java tips on http://javarevisited.blogspot.com and http://java67.com