A large number of Java developers interview for Java development positions at investment banks like Barclays (BCS), Credit Suisse (CS), and Citibank (C), but most have no idea what they will be asked.
In this article, I’m going to share some of the most common questions that programmers with more than 3 years of experience are asked.
For two years and two years of Java development experience, investment banks generally will not recruit through social recruitment, generally only after graduation through the school recruitment.
There’s no guarantee you’ll be asked these questions in an actual interview, and in fact, there’s a good chance you won’t, but this article gives you an idea of what kind of questions you’ll probably be asked. And the more prepared you are, the better you will perform in the interview.
Java programmer investment bank interview questions
Question 1: What is the problem with using HashMap in a multi-threaded environment, and when does the get() method go into an infinite loop?
A: No problem, depending on how you use it. For example, if you initialize a HashMap in one thread, and all the threads just read the data, that’s fine. For example, if a Map contains configuration information, the service will start unchanged. The real problem is when at least one thread makes changes to the HashMap, such as adding, updating, or removing any key-value pairs. Because put() causes re-sizing, which can cause infinite loops, use Hashtable or ConcurrentHashMap, which is better.
I recommend a programmer advanced architecture group: 702895049. There are shared videos in the group, there are mind mapping group announcements there are videos, they are dry goods, you can download them. Mainly share distributed architecture, high scalability, high performance, high concurrency, performance optimization, Spring Boot, Redis, ActiveMQ, Nginx, Mycat, Netty, Jvm large distributed project practice learning architect video.
Question 2: What happens if you don’t override the hashCode() method?
A: That’s a good question. From what I understand, a poor hashcode method can lead to frequent collisions of the HashMap, which can then lead to an increase in the time it takes to add an object to the HashMap.
Starting with Java 8, key collisions have less impact on performance than previous Java versions. Above a certain threshold, binary trees replace linked lists, and the worst-case O(n) performance problems of linked lists are reduced to O(logN) of binary trees.
Question 3: Do all immutable properties in Java need to be set to final?
A: No, you can achieve the same functionality by making a private variable non-final and changing it only in the constructor. Do not set the method, and if it is a mutable object, do not leak any references to the object.
Setting a reference variable to final only ensures that the variable will not be given a different reference, but you can still change the value of the reference variable’s property.
This is the one thing interviewers want to hear. If you want to learn more about reference variables in Java, I recommend Udemy Complete Java Masterclass
Q4: Implementation principle of String substring()
A: Substring takes part of the original string and creates a new object. The main point of this question is whether developers are familiar with the risk of memory leaks caused by substrings.
Until Java1.7, substring had a reference to the original character array, which meant that even a string as small as five characters could result in a 1GB character array not being garbage collected because of a strong reference.
This has been fixed in Java1.7. The original character array will not be referenced, but it will take a little longer to create substrings, which used to be O(1) and O(n) after Java 7.
Question 5: Write critical section code for a singleton pattern (answer)
A: This question is actually asking the candidate to write a double check lock.
Remember to use volatile variables to ensure singleton thread safety
Here is thread-safe singleton code written using a double check lock:
At the same time, it’s good to know typical Design patterns, such as singleton, factory, decorator, etc. If you’re interested in this, the Design Pattern Library is a good one.
Question 6: How do Java handle errors when writing or reading stored procedures?
A: This is one of the hardest questions to ask in a Java interview. My answer is that a stored procedure should return an error code when operating on an error, but catching SQLException is the only option if the stored procedure itself goes wrong.
Effective Java: 3rd Edition has a lot of good advice on Java exceptions and catching that’s worth reading.
I recommend a programmer advanced architecture group: 702895049. There are shared videos in the group, there are mind mapping group announcements there are videos, they are dry goods, you can download them. Mainly share distributed architecture, high scalability, high performance, high concurrency, performance optimization, Spring Boot, Redis, ActiveMQ, Nginx, Mycat, Netty, Jvm large distributed project practice learning architect video.
Question 7: What is the difference between executor.submit () and executer.execute ()?
Answer this interview question from my article on 50 multi-threaded interview questions. This topic is gaining popularity as the concurrency skills required of Java developers increase.
The answer is that the former returns a Future object that can be used to find the result of a worker thread’s run.
Exception handling is also different. When the task throws an exception, if it is submitted via execute(), it throws an exception that does not need to be caught (if you do not have special handling, it prints the error path system.err). If submitted via Submit (), any exception, whether checked or not, is part of the return, and Future.get will throw the exception package to the upper layer in an ExecutionExeption.
Java Concurrency Practice in Bundle If you want to learn anything Future, Callable, asynchronous computing, and improve your concurrent programming skills, we recommend you take Java Concurrency Practice in Bundle.
This is an advanced course based on concurrent programming practices written independently by Brian Goetz. This course is well worth your money and time. Concurrent programming is difficult and there are many techniques, books and courses are a good way to learn them together.
Question 8: What is the difference between the factory pattern and the abstract factory pattern? (the answer)
A: The Abstract Workshop pattern provides a multi-level abstraction. Considering different factory inherit from one abstract factory, on behalf of the creation, based on the structure of plants of different objects, for example, AutomobileFactory, UserFactory, RoleFactory inherit from AbstractFactory, etc. Each individual factory represents the creator of that type of object.
If you want to learn more about abstract factory design patterns, I suggest you take a look at Java Design Patterns, which provides excellent real-world examples to help you better understand design patterns.
Here is a UML diagram of a factory pattern and an abstract factory pattern:
If you want more options, you can also check out this course :5 Design Patterns
Question 9. What is a singleton? Is it better to use synchronized for the whole method or only for the critical sections? (the answer)
A: A singleton in Java is a class that has only one instance in the entire Java application. For example, java.lang.Runtime is a singleton class.
Creating a singleton was very difficult before Java 4, but since Java 5 introduced enumeration: enum, it has become much easier.
You can see in my article how to create thread-safe singletons in Java using enumerations and double check locks.
Q10: How can you iterate over HashMap values based on Java 4 and Java5?
This is a tricky one, but you usually use a while or for loop. There are four ways to iterate over a Map in Java. One is keySet(), which iterates over each key using the get() method to fetch the value, but it’s a bit slow. The second method is to use entrySet(). Then use the for each loop or iterator.hashNext () method to iterate over the values. (keySet, entrySet, foreach, Iterator, etc.)
This is better because at each iteration, the key and the value are already out, so you don’t need to call get() to get the value, use get() when you’re fetching data from a large list in a bucket, order n time.
You can see the details and sample code in my blog 4 Ways to Iterate Java Map.
Question 11: When do you override the hashCode() and equals() methods? (the answer)
A: When you need to, especially if you want to check whether two objects are equal by business logic, not whether the two objects perform the same address. For example, two employee objects are equal when emp_id is equal, even though they are two different objects created in different code.
In addition, if you use an object as the key of a HashMap, you must override both methods.
As part of the Java equal-HashCode constraint, when you override equals, you must override hashcode. Otherwise you can’t use them in classes like Set and Map, because they rely on equals() to ensure logical correctness.
You can also read my article to understand the problems that overwriting these two methods can cause: 5 Tips for Java Equals
I recommend a programmer advanced architecture group: 702895049. There are shared videos in the group, there are mind mapping group announcements there are videos, they are dry goods, you can download them. Mainly share distributed architecture, high scalability, high performance, high concurrency, performance optimization, Spring Boot, Redis, ActiveMQ, Nginx, Mycat, Netty, Jvm large distributed project practice learning architect video.
12. What problems did you encounter when overwriting the hashCode() method?
A: Constraints in equals and HashCode do not take effect if you do not override the equals method. According to this constraint, two objects equal through equals() must have the same Hashcode.
In this case, another object might return a different hashCode and store it at that location, which would break the immutable nature of the HashMap class because it does not support duplicate keys.
When you add an object using the put() method, it iterates through all map.entry objects at the previous bucket position in the map and updates them to the new value. If the Map already contains that Key, this mechanism will not work if hashCode is not overwritten.
If you want to learn more about the equals() and hashCode() methods on Java collections (Map, Set), I suggest you take a look at this course Java Basics: Collections.
Question 13: Which is better, the critical section of the synchroize getInstance() method or synchronize the entire getInstance() method? (the answer)
A: The answer is only synchronize critical region. Because if you lock the whole method, every time you call that method, you have to wait, even if you’re not creating an object.
In other words,synchronization only takes effect when you create the object. Once the object is created, no synchronization is required. In practice, this method takes very little time. The synchronization method takes 10 to 20 times more time than just synchronizing the critical region.
Here is a UML diagram of the singleton pattern:
By the way, there are several ways to create thread-safe singletons, including enumerations, which we can also mention in this context.
If you want to learn more, check out this free tutorial on Java Creative design patterns
Question 14: When do equals() and hashCode() methods come into play in the get() operation of a HashMap? (the answer)
A: This question is a step up from the previous one. Candidates need to know that if you mention hashCode, you will most likely be asked about applications in HashMap.
Once you provide a key object, the HashCode method is called to calculate the bucket position. A bucket contains a linked list, and each map.entry object uses equals() to see if a value with the same key already exists.
It is highly recommended that you read my blog on how HashMap works in Java to help you learn this topic.
Question 15: How to avoid deadlocks in Java (answer)
A: A deadlock occurs when two threads attempt to acquire a resource held by the other. But for this to happen, the following four conditions must be met:
- Mutually exclusive – at least one process must be in non-shared mode
- Hold and wait – a process must hold one resource and wait for another
- No preemption – Resources cannot be preempted
- Circular wait – there is a collection of processes
Deadlocks can be avoided by breaking the loop wait. You can do this by specifying in your code the order in which locks are acquired and released.
If multiple locks are acquired and released in a consistent order, there is no waiting for each other to release the lock.
You can check out my blog on how to avoid deadlocks for sample code and a more detailed explanation. It is also recommended to use concurrency and multithreading on common Java patterns to better understand multithreading patterns.
Question 16: What is the difference between creating a string with double quotes and using new()?
A: When new() is used to create strings, instances are created in the heap and are not added to the String constant pool. When created from literals, instances are placed in the permanent String constant pool in the heap.
String STR = new String(“Test”) will not put STR in the String constant pool, we need to call the string.intern () method, which will put it in the String constant pool.
When we create strings using String literals, such as String s = “Test”, Java automatically puts them into the String constant pool.
In addition, if we pass in a String literal like “Test”, another object will be created :”Test” in the String constant pool
This was my intellectual blind spot until readers gave me suggestions on my blog, and if you want to learn more about String literals and String objects, look here
I recommend a programmer advanced architecture group: 702895049. There are shared videos in the group, there are mind mapping group announcements there are videos, they are dry goods, you can download them. Mainly share distributed architecture, high scalability, high performance, high concurrency, performance optimization, Spring Boot, Redis, ActiveMQ, Nginx, Mycat, Netty, Jvm large distributed project practice learning architect video.
17. What is an immutable object? Can you write an immutable class? (the answer)
A: An immutable object is an object of a Java class that is created and cannot be modified. The modification of any immutable object object is done at creation time; for example, String is immutable in Java
Most immutable classes are final, which prevents immutable invalidation by subclass overriding methods.
You can achieve the same functionality by making members non-final but private, and unmodifiable by any method other than the constructor.
Also, make sure you do not expose the interior of an immutable object, especially if it contains mutable members.
Also, when you receive mutable objects from the client, such as java.util.date, use the clone() method to get a separate copy, preventing the risk of maliciously modifying mutable objects.
The same optimization needs to be performed when a mutable member is returned. Return another independent copy to the client; Do not return a raw reference to a mutable object. You can also check out my blog on how to create an immutable object in Java, with step-by-step instructions and sample code.
Question 18: There is a simple way to find the running time of a method without using a performance analysis tool
A: Record the time before and after the request and calculate the time difference. If a method takes too little time to display 0 milliseconds, make the method large enough, such as repeating it enough times. Total time.
Question 19: What two methods need to be implemented when you use Object as a key in a HashMap?
A: In order to have objects as keys in a hashMap or hashtable, it must implement the equals and HashCode methods.
You can also read about how Java works in HashMap for implementation details.
Question 20: How do I prevent clients from instantiating your concrete classes directly? For example, you have a Cache interface and two implementation classes: MemoryCache and DiskCache. How do I ensure that no objects of either class are created with the new() keyword?
A: Before I give an answer, research this question for yourself. I’m sure you can find the right answer, but from a code maintenance perspective, controlling your classes is very important.
I recommend a programmer advanced architecture group: 702895049. There are shared videos in the group, there are mind mapping group announcements there are videos, they are dry goods, you can download them. Mainly share distributed architecture, high scalability, high performance, high concurrency, performance optimization, Spring Boot, Redis, ActiveMQ, Nginx, Mycat, Netty, Jvm large distributed project practice learning architect video.
Now you are ready for your Java interview
These are some of the most common questions about data structures and algorithms that can help you prepare for a technical interview with an investment bank. Good luck!