Translate

Wednesday, November 7, 2018

Top 20 Java Interview Questions by Hiring Investment Banks


Source: https://dzone.com/articles/top-20-java-interview-questions-with-answers

by Javin Paul Oct. 31, 2018

Need help preparing for your interview? Check out this post where we look at the top 20 interview questions by investments banks for Java developers.

There are a lot of Java developers interviewing for Java development roles in investment banks like Barclays, Credit Suisse, and Citibank. But, many of them don’t have any idea what kinds of questions they to expect.
In this article, I’ll share a couple of frequently asked questions from investment banks for Java developers with more than three years of experience.
Yes, these questions are not refreshers or for those with one to two years of professional Java experience, as banks often don’t hire them via open interviews; they mostly join as graduate trainees.
It’s not guaranteed that you will get these questions — in fact, you most likely won’t, but this will give you an idea of the kinds of questions you can expect. Most importantly, the more you prepare, the better your interview will be.
Additionally, if these 20 questions are not enough, check out these additional 40 Java interview questions for phone interviews and these 200+ Java interview questions from the last five years as well.
Now, let's get into it! Without wasting any more of your time, let’s dive into some of the common Java interview questions from investment banks, which I have collected from friends and colleagues who have interviewed with investment banks.

Java Investment Bank Interview Questions for Programmers

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

Answer: Well, nothing is wrong; it just depends upon how you use it. For example, if you initialize a HashMap by just one thread and 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 thread is updating the HashMap, i.e. adding, changing, or removing any key-value pair.
Since the put() operation can cause re-sizing and lead to an infinite loop, that’s why either you should use Hashtable or ConcurrentHashMap, later is even better.

Question 2. If we do not override thehashCode()method, does this have any performance implications?

This is a good question. As per my knowledge, a poor hashcode function will result in the frequent collision in HashMap, which eventually increases the time for adding an object to the HashMap.
From Java 8 onwards, though collision will not impact performance as much as it does in earlier versions, 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: Do all the properties of an Immutable Object need to be final in Java?

Not necessary. You can achieve the same functionality by making a member non-final but private and not modifying them except in the 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, but you can still change individual properties of an object that are pointed by that reference variable.
This is one of the key points that interviewers like to hear from candidates. If you want to know more about final variables in Java, I recommend joining The Complete Java MasterClass, which is updated for Java 11 on Udemy.

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

This is another good Java interview question. Here it is: “The substring creates a new object out of source string by taking a portion of 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 that even a sub-string of five characters long can prevent a 1GB character array from garbage collection by holding 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 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.

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

This core Java question is another common question and expects the candidate to write Java singletons 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 that same note, it’s good to know about classical design patterns, likes Singleton, Factory, Decorator, etc. If you are interested in this, then the Design Pattern library is a good collection for that.

Question 6: How do you handle an error condition while writing a stored procedure or accessing stored procedure from Java? 

This is one of the toughest Java interview questions, and again, its open for you all — my friend didn’t know the answer and didn’t mind sharing it with me.
My take is that a stored procedure should return an error code if some operation fails, but if a stored procedure fails itself, then catching the SQLException is the only choice.
Effective Java: 3rd Edition also has some good advice on dealing with error and exceptions in Java, which is worth reading.

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

This Java interview question is from my list of Top 50 Java multi-threading question answers. It’s getting popular in the interview setting because of the increasing demand for Java developers with good concurrency skills.
The answer to this question is that the 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 the submit() method, any thrown exception — checked exception or not — is 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 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 the bible for some Java Developers. The course is definitely worth your time and money. Since Concurrency is a tough and tricky topic, a combination of this book and course is the best way to learn it.

Question 8: What is the difference between the Factory and the Abstract Factory pattern? (answer)

Answer: The Abstract Factory pattern provides one more level of abstraction. Consider the different factories each extended from an Abstract Factory and responsible for the creation of different hierarchies of objects based on the type of factory, for example, AbstractFactory extended by  AutomobileFactoryUserFactory , RoleFactory, etc. Each individual factory would be responsible for the creation of objects in that genre.
If you want to learn more about Abstract Factory design pattern, then I suggest you check out Design Pattern in Java course, which provides nice, real-world examples to better understand patterns.
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 whole Java application. For example, java.lang.Runtime is a Singleton class.
Creating a Singleton was tricky prior to Java 4, but once Java 5 introduced enum, it became very easy.
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)

This is a tricky one, but we managed to write one using while and a for  loop. Actually, there are four ways to iterate over any Map in Java. One involves using keySet() and iterating over a key and then using the get() method to retrieve values, which is a bit expensive.
The second method involves using entrySet() and iterating it over either by using the  for each loop or with the Iterator.hasNext() method.
This one is a better approach because both key and value objects are available to you during Iteration, and you don’t need to call the 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 learn more in my post 4 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 perform an equality check based upon business logic rather than object equality, e.g. two employee objects are equal if they have the same emp_id, despite the fact that they are two different objects created by different parts of the code.
Also, overriding both these methods is a must if you want to use them as a 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 the invariant of classes, e.g. Set and Map, which relies on the equals() method for functioning properly.
You can also check my post on the top  5 tips on equals in Java to understand subtle issues that can arise while dealing with these two methods.

Question 12: What problems will you face if you don’t override the hashCode() method? (answer)

If you don’t override the equals method, then the contract between equals and hashcode will not work, according to which, two objects that are equal by equals() must have the same hashcode.
In this case, another object may return a different hashCode and will be stored on that location, which breaks the invariant of the 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 this Java Fundamentals: Collections course on Pluralsight by Richard Warburton

Question 13 : Is it better to synchronize critical section of the getInstance() method or the whole getInstance() method? (answer)

The answer is an only critical section, because if we lock the whole method so 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 only happens once.
Once an object is created, there is no need for any synchronization. In fact, that’s very poor coding in terms of performance, as the synchronized method reduces performance up to 10 to 20 times.
Here is 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 do the equals() and hashCode() methods come into the picture during the get() operation on the HashMap(answer)

This core Java interview question is a follow-up of previous Java questions, and the candidate should know that once you mention hashCode, people are most likely to ask how they are used in HashMap.
When you provide a key 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 objects is evaluated by using the  equals()method to see if they contain the actual key 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 that are held by each other, but for that to 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  — A set of processes must exist.
You can avoid deadlock by breaking the circular wait condition. In order to do that, you can make arrangements in the code to impose the ordering on acquisition and release of locks.
If the lock is acquired in a consistent order and released in the opposite order, there would not be a situation where one thread is holding a lock, which is acquired by the other 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 a String as new() and literal? (answer)

When we create a String object in Java with the new() Operator, it’s created in a heap and not added into the String pool, while String created using the literal is 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 the  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”, that Java automatically puts that into the String pool.
By the way, there is a catch here: since we are passing arguments as a “Test," which is a String literal, it will also create as another object: “Test” on string pool.
This is the one point that has gone unnoticed until knowledgeable readers from my blog suggested it. To learn more about the difference between a String literal and String object, see this article.
Here is a nice image that shows this difference quite well:

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

Immutable classes are Java classes whose objects cannot be modified once created. Any modification in the Immutable object results in the new object, for example, String is immutable in Java.
Mostly Immutable classes are final in Java in order to prevent subclasses from overriding methods, which can compromise Immutability.
You can achieve the same functionality by marking the member as non-final but private and not modifying them except in the constructor.
Apart from the obvious, you also need to make sure that you do not expose the internals of an Immutable object, especially if it contains a mutable member.
Similarly, when you accept the value for the mutable member from the client, e.g.,java.util.Date, use the clone() method 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 a value for a mutable member. Return another separate copy to the client; never return the original reference held by the Immutable class. You can also see my post How to create an Immutable class in Java for a 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 method for execution.
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 that is big enough, in the sense that the one is doing a considerable amount of processing

Question 19: Which two methods do you need to implement an Object as a key in the HashMap? (answer)

In order to use any object as the Key in theHashMap or Hashtable, it must implement the equals and hashcode method in Java.
You can also read How HashMap works in Java for a detailed explanation on how the equals and hashcode method is used to put and get an object from the 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 DiskCacheHow do you ensure that there is no object from these two classes that is created by the client using the new() keyword?

I leave this question for you to practice and think about before I give the answer. I am sure you can figure out the right way to do this, as this is one of the important decisions to keep control of classes in your hand — great from a maintenance perspective.

Now, You’re Ready for the Java Interview!

These are some of the most common questions outside of data structure and algorithms that help you prepare for your interview with an investment bank. Good luck!

Further Learning

  1. The Complete Java Masterclass
  2. Java Fundamentals: The Java Language
  3. Core Java SE 9 for the Impatient
  4. 200+ Java Interview questions