There are a lot of trying for Java development role on Investment banks like Barclays, Credit Suisse, Citibank etc, but many of them don’t have any idea of what kind of questions they can expect there. Java developers In this article, I’ll share a couple of frequently asked questions from investment banks to Java developer of more than 3 years of experience. Yes, these questions are not for or experienced professional as often banks don’t hire them via open interviews, they mostly join as graduate trainees. freshers 1 to 2 years of Java , in fact, 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. It’s not guaranteed that you will get these questions Btw, if you think 21 is not enough and you need more than check out these additional for the telephonic interview and these from last 5 years as well. 40 Java questions 200+ Java questions 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 common Java interview questions from banks, which I have collected from some of my friends and colleagues appeared on interviews of these banks. Java Interview Questions from Investment Banks ( )Answer: Well, nothing is wrong, it depends upon how you use. For example, if you by just one thread and then all threads are only reading from it, then it’s perfectly fine. Question 1: What’s wrong using HashMap in the multi-threaded environment? When get() method go to the infinite loop? answer initialize a HashMap One example of this is a . Map which 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 infinite loop, that’s why either you should use or , later is even better. Hashtable ConcurrentHashMap ( )This is a good question and opens to all, as per my knowledge, a poor hash code function will result in the which eventually increases the time for adding an object into Hash Map. Question 2. Does not overriding hashCode() method has any performance implication? answer frequent collision in HashMap From onwards though collision will not impact performance as much as it does in earlier versions because after a threshold the will be replaced by a , which will give you performance in the worst case as compared to O(n) of a linked list. Java 8 linked list binary tree O(logN) ( ) Question 3: Does all property of 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 , only ensures that it will not be reassigned a different value, but you can still change individual properties of an object, pointed by that reference variable. making a reference variable final This is one of the key points, Interviewer likes to hear from candidates. If you want to know more about final variables in Java, I recommend joining on Udemy, one of the best, hands-on course. The Complete Java MasterClass ( ) 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 original string” This question was mainly asked to see if the developer is familiar with the risk of , which sub-string can create. memory leak Until Java 1.7, substring holds the reference of the original character array, which means even a sub-string of 5 characters long, , by holding a strong reference. can prevent 1GB character array from garbage collection This issue was fixed in Java 1.7, where 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. Btw, if you want to learn more about memory management in Java, I recommend to check out course By Kevin Jones on Pluralsight. Understanding the Java Virtual Machine: Memory Management ( )This core Java question is another common question and expecting the candidate to write Java singleton using . Question 5: Can you write a critical section code for the singleton? answer double-checked locking Remember to use a to make Singleton . volatile variable 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 is a good collection of that. Design Pattern library ( ) Question 6: How do you handle error condition while writing a stored procedure or accessing stored procedure from java? answer This is one of the and again its open for you all, my friend didn’t know the answer so he didn’t mind telling me. tough Java interview questions My take is that a stored procedure should return an error code if some operation fails but if stored procedure itself fails than catching is the only choice. SQLException The also has some good advice on dealing with error and exceptions in Java, which is worth reading. Effective Java 3rd Edition ( ) Question 7 : What is difference between Executor.submit() and Executer.execute() method ? answer This Java interview question is from my list of , It’s getting popular day by day because of the huge demand of a Java developer with good concurrency skill. Top 50 Java multi-threading question answers Answer of this Java interview question is that former returns an object of which can be used to find the result from a worker thread) Future 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() method any thrown exception, or not, is the part of the task’s return status. checked exception 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 course by Java Champion Heinz Kabutz. Java Concurrency Practice in Bundle It’s an advanced course, which is based upon the classic book by none other than , which is considered as a bible for 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. Java Concurrency Practice Brian Goetz ( )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 individual factory would be responsible for the creation of objects in that genre. Question 8: What is the difference between factory and abstract factory pattern? answer If you want to learn more about Abstract Factory design pattern then I suggest you check out course, which provides nice, real-world example to understand patterns better. Design Pattern in Java Here is UML diagram of factory and abstract factory pattern: If you need more choices, then you can also check out my list of courses. Top 5 Java Design Pattern ( )Singleton in Java is a class with just one instance in whole Java application, for example, java.lang.Runtime is a Singleton class. Question 9: What is Singleton? is it better to make the whole method synchronized or only critical section synchronized? answer Creating Singleton was tricky prior to Java 4 but once Java 5 introduced it's very easy. Enum You can see my article for more details on writing Singleton using the enum and double checked locking which is the purpose of this Java interview question. How to create thread-safe Singleton in Java ( )Tricky one, but he managed to write using while and a for loop. Actually, there are four ways to iterate over any Map in Java, one involves using and iterating over a key and then using method to retrieve values, which is bit expensive. Question 10: Can you write code for iterating over HashMap in Java 4 and Java 5? answer keySet() get() The second method involves using and iterating over them either by using or while with Iterator.hasNext() method. entrySet() for each loop This one is a better approach because both key and value object are available to you during Iteration and you don’t need to call method for retrieving the value, which could give the O(n) performance in case of a huge at one bucket. get() linked list You can further, see my post for detailed explanation and code examples. 4 ways to iterate over Map in Java ( )Whenever necessary especially if you want to do equality check based upon business logic rather than object equality e.g. two employee object are equal if they have the same emp_id, despite the fact that they are two different objects, created by different part of the code. Question 11 : When do you override hashCode() and equals()? answer Also both these methods are must if you want to use them as key in . overriding 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 method for functioning properly. equals() You can also check my post to understand subtle issue which can arise while dealing with these two methods. 5 tips on equals in Java ( )If you don’t override 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 . Question 12: What will be the problem if you don’t override hashCode() method? answer same hashcode In this case, another object may return different hashCode and will be stored on that location, which breaks invariant of because they are not supposed to allow duplicate keys. HashMap class When you add the object using put() method, it iterates through all Map.Entry objects present in that bucket location, and update value of the previous mapping, if Map already contains that key. This will not work if 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 course on Pluralsight by Richard Warburton Java Fundamentals: Collections ( )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. Question 13 : Is it better to synchronize critical section of getInstance() method or whole getInstance() method? answer In other words, is only needed, when you create an object, which happens only once. synchronization Once an object has created, there is no need for any synchronization. In fact, that’s very poor coding in terms of performance, as synchronized method reduce performance up to 10 to 20 times. Here is UML diagram of : Singleton design pattern By the way, there are several ways to create a thread-safe singleton in Java, including , which you can also mention as part of this question or any follow-up. Enum If you want to learn more, you can also check to — A #FREE Course from Udemy. Learn Creational Design Patterns in Java ( )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. Question 14: Where does equals() and hashCode() method comes in the picture during the get() operation on HashMap? answer 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 object is evaluated by using equals() method to see if they contain the actual key object or not. I strongly suggest you read my post, , another tale of an interview to learn more about this topic. How HashMap works in Java ( )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: Questions 15: How do you avoid deadlock in Java? answer Mutual exclusionAt least one process must be held in a non-sharable mode. Hold and WaitThere must be a process holding one resource and waiting for another. No preemptionresources cannot be preempted. Circular WaitThere must exist a set of processes You can avoid deadlock by breaking the . In order to do that, you can make arrangement in the code to impose the on acquisition and release of locks. circular wait condition ordering If lock will be acquired in a consistent order and released in just opposite order, there would not be a situation where one thread is holding a lock which is acquired by other and vice-versa. You can further see my post, for the code example and a more detailed explanation. how to avoid deadlock in Java I also recommend, By on Pluralsight for a better understanding of concurrency patterns for Java developers. Applying Concurrency and Multi-threading to Common Java Patterns José Paumard ( )When we create a string object in Java with new() Operator, it’s created in and not added into string pool while String created using are created in String pool itself which exists in PermGen area of heap. Question 16: What is the difference between creating String as new() and literal? answer heap literal String str = new String(“Test”) does not put the object str in String pool, we need to call method which is used to put them into String pool explicitly. String.intern() It’s only when you create a String object as String literal e.g. String s = “Test” Java automatically put that into 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 . string pool This is the one point, which has gone unnoticed until knowledgeable readers of blog suggested it. To learn more about the difference between a String literal and String object, see article. Javarevisited this Here is a nice image which shows this difference quite well: ( )Immutable classes are Java classes whose objects cannot be modified once created. Any modification in Immutable object results in the new object, for example, . Question 17: What is Immutable Object? Can you write Immutable Class? answer String is immutable in Java Mostly Immutable classes are also in Java, in order to prevent subclasses from overriding methods, which can compromise Immutability. final You can achieve the same functionality by making member as non-final but and not modifying them except in constructor. private Apart from obvious, you also need to make sure that, you should 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 client e.g. java.util.Date, use keep a separate copy for yourself, to prevent the risk of malicious client modifying mutable reference after setting it. clone() method 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 for step by step guide and code examples. How to create an Immutable class in Java ( )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. Question 18: Give the simplest way to find out the time a method takes for execution without using any profiling tool? answer 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 the sense the one which is doing a considerable amount of processing ( )In order to use any object as Key in HashMap or Hashtable, it must implement and method in Java. Question 19: Which two method you need to implement to use an Object as key in HashMap? answer equals hashcode You can also read for a detailed explanation on how equals and hashcode method is used to put and get an object from HashMap. How HashMap works in Java 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 decision to keep control of classes in your hand, great from a maintenance perspective. 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 this two classes is created by the client using new() keyword. Further Learning The Complete Java Masterclass Java Fundamentals: The Java Language Core Java SE 9 for the Impatient 200+ Java Interview questions Closing Notes Great!!, you made it to the end of the article… Good luck on 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 ( ) on Medium if you’d like to be notified on my new post, and don’t forget to follow me on javinpaul Twitter !