20 Most Asked Core Java Interview Questions in Investment Banking: UBS, Fiserv, HSBC, and Deutsche Bank.

20 Most Asked Core Java Interview Questions in Investment Banking: UBS, Fiserv, HSBC, and Deutsche Bank.









Explore the following 20 essential Core Java interview questions for investment banking roles at UBS, Fiserv, HSBC, and Deutsche Bank. Gain insights on OOP, multithreading, and performance optimization for fintech applications.

Introduction

In the high-stakes world of investment banking, mastering Core Java is not just an asset—it's a necessity. As technology revolutionizes financial markets, institutions like UBS, Fiserv, HSBC, and Deutsche Bank are looking for Java developers who can navigate the complex intersection of finance and technology. This blog post dives into the 20 most frequently asked Core Java interview questions in the investment banking sector, offering insights that go beyond basic coding knowledge. From leveraging object-oriented principles to model sophisticated financial instruments, to optimizing high-frequency trading systems with advanced multithreading techniques, we'll explore how Java's robust features are applied in real-world financial scenarios. We'll unravel the intricacies of data structures best suited for order books, delve into design patterns that enhance trading platform flexibility, and discuss performance optimization strategies critical for low-latency operations. Whether you're a seasoned developer looking to transition into fintech or a fresh graduate aiming to break into investment banking, this guide will equip you with the knowledge to confidently tackle technical interviews. Prepare to explore Java's role in shaping modern finance, and arm yourself with the expertise that top-tier banks demand in today's data-driven markets.


1. How does substring() inside String work?

The substring() method in Java returns a new string that is a substring of the given string. It takes two parameters: the beginning index (inclusive) and the end index (exclusive).

Internally, substring() creates a new String object but does not copy the entire character array. Instead, it creates a new string that shares the original character array, but with different offset and count values. This allows for efficient memory usage, but can also lead to memory leaks if a large original string is referenced by many substrings.



2. What is a classloader?

A classloader in Java is a part of the Java Runtime Environment (JRE) that dynamically loads Java classes into the Java Virtual Machine (JVM). The classloaders follow a delegation model:

Bootstrap ClassLoader: Loads the core Java libraries located in the <JAVA_HOME>/lib directory.

Extension ClassLoader: Loads the libraries located in the <JAVA_HOME>/lib/ext directory or any other specified extension directory.

System/Application ClassLoader: Loads the application-specific classes from the classpath (environment variable CLASSPATH).



3. How is the creation of a String using new() different from that of a literal?

String Literal: When a string literal is created, it is interned, meaning it is stored in a common pool and can be reused, improving memory efficiency. For example, String s1 = "Hello"; reuses the literal if it already exists in the pool.

new Keyword: When you create a string using the new keyword, it creates a new string object in the heap, bypassing the string pool. For example, String s2 = new String("Hello"); always creates a new object even if the same string already exists in the pool.



4. What is the difference between Executor.submit() and Executor.execute() method?

Executor.submit(): Returns a Future object that can be used to retrieve the result of the task or to check its status. This method is useful when you need to get the result of a task.

Executor.execute(): Does not return any value. It is used when you do not need to retrieve the result of the task, often for fire-and-forget tasks.





5. What do you understand by Java Memory Model?

The Java Memory Model (JMM) defines how threads interact through memory and what behaviors are allowed in multithreaded Java programs. It provides guarantees about:

Visibility: Changes made by one thread are visible to others.

Atomicity: Ensures operations like reads and writes are indivisible.

Ordering: Controls the order of operations to avoid reordering issues.



6. How to make a class Immutable? What purpose does it solve?

To make a class immutable:

Declare the class as final so it cannot be subclassed.

Make all fields private and final.

Provide no setters.

Ensure mutable objects are not directly accessible and do not provide methods that modify these objects.

Provide a constructor to initialize all fields.

Purpose:

Immutability ensures thread-safety since the state of an immutable object cannot be changed after it is created.

Simplifies concurrent programming by avoiding synchronization issues.

Useful as a key in collections like HashMap and HashSet.



7. Can you use HashMap in a multi-threaded environment? What can be the problem?

Using HashMap in a multi-threaded environment can lead to:

Race conditions: Multiple threads modifying the map simultaneously can corrupt its state.

Non-deterministic behavior: Unpredictable results due to concurrent modifications.

Infinite loops: Specifically, during rehashing, which can cause the application to hang.



8. Can you write a critical section code for the singleton?

public class Singleton {

    private static volatile Singleton instance;

    private Singleton() {

        // Private constructor to prevent instantiation

    }

    public static Singleton getInstance() {

        if (instance == null) {

            synchronized (Singleton.class) {

                if (instance == null) {

                    instance = new Singleton();

                }

            }

        }

        return instance;

    }

}



9. What is Singleton? Is it better to make the whole method synchronized or only the critical section synchronized?

A Singleton ensures that a class has only one instance and provides a global point of access to it.

Whole method synchronized: Simplifies implementation but can lead to performance bottlenecks due to unnecessary synchronization.

Critical section synchronized: Improves performance by reducing the scope of synchronization to only the critical part of the code.



10. How do you avoid deadlock in Java?

To avoid deadlock:

Avoid nested locks: Do not acquire multiple locks at once.

Lock ordering: Always acquire locks in a consistent order.

Timeouts: Use tryLock with timeout to avoid waiting indefinitely.

Deadlock detection: Monitor and analyze thread dumps to detect deadlocks.



11. How can you avoid serialization in the child class if the base class is implementing the Serializable interface?

To avoid serialization in a child class:

Override the writeObject and readObject methods in the child class and throw NotSerializableException.

private void writeObject(ObjectOutputStream oos) throws IOException {

    throw new NotSerializableException("Serialization is not allowed");

}

private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {

    throw new NotSerializableException("Deserialization is not allowed");

}

12. What is the ConcurrentHashMap in Java and how do you implement it?

ConcurrentHashMap is a thread-safe version of HashMap designed for concurrent use. It uses a combination of techniques such as segmentation and fine-grained locking to allow concurrent access and modification without locking the entire map.

ConcurrentHashMap<Integer, String> map = new ConcurrentHashMap<>();

map.put(1, "one");

String value = map.get(1);



13. Explain the FailFast iterator and FailSafe iterator along with examples for each.

FailFast Iterator: Throws a ConcurrentModificationException if the underlying collection is modified during iteration.

Example: ArrayList, HashMap.



List<String> list = new ArrayList<>();

Iterator<String> iterator = list.iterator();

while (iterator.hasNext()) {

    if (someCondition) {

        list.add("newElement"); // Causes ConcurrentModificationException

    }

    iterator.next();

}

FailSafe Iterator: Does not throw an exception if the collection is modified during iteration. It works on a copy of the collection.

Example: ConcurrentHashMap.

ConcurrentHashMap<Integer, String> map = new ConcurrentHashMap<>();

Iterator<Integer> iterator = map.keySet().iterator();

while (iterator.hasNext()) {

    map.put(3, "three"); // No ConcurrentModificationException

    iterator.next();

}



14. What is the difference between Checked Exception and Unchecked Exception?

Checked Exception: Subclasses of Exception (excluding RuntimeException). These must be handled explicitly in the code using try-catch or by declaring them in the method signature using throws.

Example: IOException, SQLException.

Unchecked Exception: Subclasses of RuntimeException. These are not required to be caught or declared thrown. They indicate programming errors like logical mistakes or incorrect API usage.

Example: NullPointerException, ArrayIndexOutOfBoundsException.

15. What is the difference between factory and abstract factory pattern?

Factory Pattern: Provides a method for creating objects without specifying the exact class of object that will be created. Used for creating a single family of objects.

Example:

public interface Shape {

    void draw();

}

public class Circle implements Shape {

    public void draw() {

        System.out.println("Drawing Circle");

    }

}

public class ShapeFactory {

    public Shape getShape(String shapeType) {

        if (shapeType == null) {

            return null;

        }

        if (shapeType.equalsIgnoreCase("CIRCLE")) {

            return new Circle();

        }

        return null;

    }

}

Abstract Factory Pattern: Provides an interface for creating families of related or dependent objects without specifying their concrete classes. Used for creating related objects.

Example:

public interface Shape {

    void draw();

}

public interface Color {

    void fill();

}

public class Circle implements Shape {

    public void draw() {

        System.out.println("Drawing Circle");

    }

}

public class Red implements Color {

    public void fill() {

        System.out.println("Filling Red");

    }

}

public abstract class AbstractFactory {

    abstract Color getColor(String color);

    abstract Shape getShape(String shape);

}

public class ShapeFactory extends AbstractFactory {

    public Shape getShape(String shapeType) {

        if (shapeType == null) {

            return null;

        }

        if (shapeType.equalsIgnoreCase("CIRCLE")) {

            return new Circle();

        }

        return null;

    }

    public Color getColor(String color) {

        return null;

    }

}

public class FactoryProducer {

    public static AbstractFactory getFactory(String choice) {

        if (choice.equalsIgnoreCase("SHAPE")) {

            return new ShapeFactory();

        }

        return null;

    }

}



16. What is marker interface?

A marker interface is an interface that has no methods or constants. It is used to indicate that a class possesses some property or should be processed in a certain way.

Example: Serializable, Cloneable.



17. When finally block doesn’t get executed?

The finally block may not get executed if:

The JVM exits during the try or catch block (e.g., System.exit()).

The thread executing the try or catch block gets killed.

A fatal error occurs (e.g., OutOfMemoryError, StackOverflowError).



18. How does Garbage collection in Java work?

Garbage collection in Java is the process of automatically identifying and disposing of objects that are no longer in use. The JVM uses several algorithms for garbage collection:

Mark and Sweep: Marks live objects and sweeps unmarked objects.

Generational GC: Divides objects into generations (young, old) and collects them separately.

G1 (Garbage First) Collector: Divides the heap into regions and prioritizes garbage collection in regions with the most garbage.



19. Difference between ClassNotFoundException vs NoClassDefFoundError?

ClassNotFoundException: Thrown when an application tries to load a class at runtime using Class.forName(), ClassLoader.loadClass(), or ClassLoader.findSystemClass() and the class is not found in the classpath.

NoClassDefFoundError: Thrown when the JVM or a ClassLoader tries to load the definition of a class (during the linking phase) and the class is not found. Typically occurs when a class was present at compile-time but not at runtime.

20. How to break Singleton?

Singleton can be broken by:

Reflection: Can access the private constructor.

Constructor<Singleton> constructor = Singleton.class.getDeclaredConstructor();

constructor.setAccessible(true);

Singleton instance = constructor.newInstance();

Serialization: By serializing and deserializing the object.

ObjectInputStream in = new ObjectInputStream(new FileInputStream("file"));

Singleton instance = (Singleton) in.readObject();

Cloning: By overriding clone() method.

Singleton instance = (Singleton) singleton.clone();

ClassLoaders: Loading the class with different class loaders.

To prevent these, ensure:

Throwing exceptions in the private constructor if an instance already exists.

Implementing readResolve method in serialization.

Overriding clone method to throw CloneNotSupportedException.


Conclusion

In conclusion, mastering these Core Java concepts is crucial for success in investment banking technology roles. The questions we've covered highlight the unique challenges of applying Java in finance—from optimizing high-frequency trading systems to ensuring data integrity in critical transactions. As you prepare for interviews at institutions like UBS, Fiserv, HSBC, and Deutsche Bank, focus on understanding not just the 'what', but the 'why' behind each concept. Remember, in fintech, theoretical knowledge must translate into practical, efficient solutions. Keep honing your skills, stay updated with the latest Java developments, and approach each interview as an opportunity to showcase how your expertise can drive innovation in financial technology. Your journey in mastering Java for finance is ongoing—embrace it with enthusiasm and confidence.


Thank you!


Popular posts from this blog

Software Testing Job Updates: Your Gateway to Exciting Opportunities.

Monitors in Postman and How to Set Up Monitoring Over Collections in Postman

A Comprehensive Guide on How to Prepare a Well-Structured Test Plan for Software Testing

Important API Testing Interview Questions

Manual to Automation Testing: A Complete Beginner's Roadmap.

Mastering JIRA: A 15-Day Learning Plan for Project and Test Management

Linux and Unix Commands, Shell Scripting Concepts, Operating System, for Beginners and Experts - The Essential Linux and Unix Handbook