Barclays Java Spring-Boot Micro-service Interview Question with answer 2024

Hello folks welcome to another real life interview transcript from a banking giant. This was for Java backend role for experienced professional having five plus of experience. From this transcript you will get know the nature of questions asked in an interview.

Ajay Rathod
19 min readMar 30, 2024

Note — If You love watching this on Youtube here is the link —

Are you preparing for a job interview as a Java developer?

Find my book Guide To Clear Java Developer Interview here Gumroad (PDFFormat) and Amazon (Kindle eBook).

Guide To Clear Spring-Boot Microservice Interview here Gumroad (PDFFormat) and Amazon (Kindle eBook).

Download the sample copy here: Guide To Clear Java Developer Interview[Free Sample Copy]

Guide To Clear Spring-Boot Microservice Interview[Free Sample Copy]

How HashMap Works internally?

HashMap is Hash table based implementation of the Map interface. This implementation provides all of the optional map operations, and permits null values and the null key. (The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls.) This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.

Here is the working:

  • Java HashMap allows null key and null values.
  • HashMap is not an ordered collection. You can iterate over HashMap entries through keys set but they are not guaranteed to be in the order of their addition to the HashMap.
  • HashMap is almost similar to Hashtable except that it’s unsynchronized and allows null key and values.
  • HashMap uses it’s inner class Node<K,V> for storing map entries.
  • HashMap stores entries into multiple singly linked lists, called buckets or bins. Default number of bins is 16 and it’s always power of 2.
  • HashMap uses hashCode() and equals() methods on keys for get and put operations. So HashMap key object should provide good implementation of these methods. This is the reason immutable classes are better suitable for keys, for example String and Interger.
  • Java HashMap is not thread safe, for multithreaded environment you should use ConcurrentHashMap class or get synchronized map using Collections.synchronizedMap() method.

Difference between Put and Post?

.The PUT method is typically used to create resources if they don’t exist and update them if they do, while the POST method is primarily used only for creating new resources.

Note — In Java Interview always expect one question from HTTP methods like put vs post and so on.

Write a program to reverse the array of string without using predefined method?

Basically, Interviewer wants to know if you can write code manually apart from using existing Java API to do this.

public class ReverseArrayWithoutPredefinedMethod {

public static void main(String[] args) {
// Sample array of strings
String[] array = {"apple", "banana", "orange", "grape"};

// Printing original array
System.out.println("Original array:");

// Reversing the array

// Printing reversed array
System.out.println("\nReversed array:");

// Method to reverse the array of strings
public static void reverseArray(String[] arr) {
int start = 0;
int end = arr.length - 1;

// Swap elements from start to end until mid is reached
while (start < end) {
// Swapping elements
String temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;

// Moving pointers towards the center

// Method to print the array of strings
public static void printArray(String[] arr) {
for (String s : arr) {
System.out.print(s + " ");

Similarly there might be one more question on this, Reverse a string without using Java API or any Reverse methods.

Difference between comparable and comparator?

The most fundamental difference between Comparable and Comparator in Java is the number of sorting sequences they support:

  • Comparable: Supports a single sorting sequence based on the object’s natural ordering (often defined by a single field).
  • Comparator: Offers the ability to define multiple sorting sequences based on your custom logic, potentially using multiple fields for comparison.


  • Defines a natural ordering for a class’s objects.
  • Implemented by the class itself using the compareTo(Object o) method.
  • This method returns a negative integer if the current object is less than the argument (o), zero if they are equal, and a positive integer if the current object is greater.
  • Only allows sorting based on a single aspect (natural ordering) of the class.


  • Provides a separate way to define sorting logic for objects.
  • Implemented in a separate class or as an anonymous inner class.
  • Uses the compare(Object o1, Object o2) method to compare two objects and return a negative integer if the first is less than the second, zero if they are equal, and a positive integer if the first is greater.
  • Offers flexibility for defining custom sorting criteria on various object attributes.

What is jdbctemplate ,statement,preparedstatement ,callable statement?

JDBC (Java Database Connectivity) provides interfaces for interacting with relational databases in Java. Here’s a breakdown of the key concepts you mentioned:

JdbcTemplate (from frameworks like Spring):

  • JdbcTemplate is a helper class that simplifies working with JDBC APIs.
  • It abstracts away boilerplate code related to creating connections, statements, and handling exceptions.
  • You can use it to execute SQL queries and updates with features like prepared statements and parameter binding.


  • The Statement interface is the most basic way to execute SQL statements.
  • You can create a Statement object from a Connection object.
  • It allows you to execute various SQL statements like SELECT, INSERT, UPDATE, and DELETE.
  • However, Statement has limitations:
  • It cannot accept parameters directly in the SQL string, making it vulnerable to SQL injection attacks.
  • It’s less efficient for repeated executions of the same query with different data.


  • PreparedStatement is an extension of Statement that addresses the limitations mentioned above.
  • You create a PreparedStatement object by providing a pre-compiled SQL template with placeholders for parameters (represented by '?').
  • You then set the values for these parameters using setter methods before executing the statement.
  • This separation of query and data improves security (prevents SQL injection) and performance (avoids recompiling the same query repeatedly).


  • CallableStatement is another extension of Statement specifically designed for calling stored procedures in a database.
  • Stored procedures are pre-written SQL code blocks stored in the database that can be executed and potentially return results or modify data.
  • CallableStatement allows you to define parameters for the stored procedure (both input and output parameters) and execute the call.

What are these annotations @Component and @Autowired annotation?

These annotations are fundamental concepts in Spring Framework for dependency injection and managing beans. Here’s a breakdown of their roles:


  • A stereotype annotation that marks a class as a Spring bean.
  • Spring scans your project for classes annotated with @Component (or its specialized variants like @Controller, @Service, or @Repository) during application startup.
  • These classes are then managed by the Spring container, meaning Spring will:
  • Instantiate them.
  • Inject any required dependencies into them (using @Autowired).
  • Make them available for autowiring in other beans.


  • Used to inject dependencies into a bean managed by Spring.
  • You can mark fields, setter methods, or constructor arguments with @Autowired.
  • Spring will automatically find a compatible bean in the Spring application context and inject it into the field/method/constructor.
  • This simplifies dependency injection by removing the need for manual bean creation and wiring.

Relationship between @Component and @Autowired:

  • @Component marks a class as a bean that Spring manages.
  • @Autowired injects dependencies (other Spring-managed beans) into these beans.

In essence:

  • @Component is like saying "This class is a bean I want Spring to manage."
  • @Autowired is like saying "Spring, please inject the required bean dependency here."

Additional Points:

  • By default, Spring scans the base package where your main application class is located for components. You can customize this behavior using @ComponentScan annotation.
  • There are different ways to configure autowiring behavior using qualifiers if you have multiple beans of the same type.

What is SQL Injection?

SQL injection (SQLi) is a dangerous web security vulnerability. Attackers can exploit it to steal, modify, or even delete data from your database.

Imagine a web form where users enter data. If the application doesn’t properly handle that data (sanitize it), attackers can inject malicious SQL code disguised as normal input. This code then gets executed by the database, potentially causing havoc.

To prevent SQLi, follow these security measures:

  • Validate user input to make sure it’s what you expect.
  • Use special techniques (prepared statements) to separate user input from the actual SQL query.
  • Consider using stored procedures for complex queries.
  • Keep your software updated with the latest security patches.

By taking these steps, you can make your web application much more secure against SQL injection attacks.

What is session and sessionfactory in Hibernate?

In Hibernate, which is an object-relational mapper (ORM) framework for Java, Session and SessionFactory play crucial roles in interacting with your database:


  • Factory for Sessions: Think of it as a factory that creates Session objects. There's typically one SessionFactory per application.
  • Configuration: It encapsulates the Hibernate configuration details like database connection information, dialect, and mappings between your Java classes and database tables.
  • Long-lived: A SessionFactory is created during application startup and remains available throughout the application's lifecycle. It's thread-safe for concurrent access.
  • Benefits:
  • Manages connection pooling for efficient database access.
  • Caches information about database schema and mappings, improving performance.


  • Database Interaction: Represents a single unit of work (transaction) with the database. You use a Session to perform CRUD (Create, Read, Update, Delete) operations on your persistent objects.
  • Short-lived: A Session is typically created, used for a specific task (transaction), and then closed to release resources. It's not thread-safe and should not be shared between threads.
  • Functionality: Provides methods for:
  • Saving, updating, and deleting persistent objects.
  • Retrieving data from the database using queries.
  • Managing transactions (commit or rollback changes).
  • First-Level Cache: Maintains a temporary cache of recently accessed objects within the Session itself, improving performance for repetitive operations.

What is HQL?

HQL stands for Hibernate Query Language. In a nutshell, it’s a special query language designed for Hibernate, a popular object-relational mapper (ORM) framework in Java. Here’s the gist:

  • Focuses on objects: HQL lets you write queries using the names of your Java classes and their properties instead of raw database tables and columns. This makes it more readable and less prone to errors compared to writing pure SQL.
  • Behind the scenes translation: When you execute an HQL query, Hibernate translates it into the corresponding SQL statement for your underlying database. This frees you from worrying about the specifics of different database dialects.

So, HQL provides a convenient and object-oriented way to interact with your database through Hibernate.

What are Joins?

joins are a fundamental concept for combining data from multiple tables. They allow you to retrieve related information from different tables based on a shared field. Imagine you have a database for an online store:

  • One table (customers) stores customer information like names and IDs.
  • Another table (orders) stores details about orders, including the customer ID (linking it to the customers table).

To get a complete picture, you might want to combine customer details with their corresponding orders. This is where joins come in.

Here are the different types of joins you can use to achieve various results:

  • Inner Join: This is the most common type. It returns only rows where there’s a match in both tables based on the join condition. For example, you could retrieve customer names and their corresponding order details.
  • Left Join: This includes all rows from the left table (the one you specify first), and matching rows from the right table. Rows from the right table with no match on the join condition will have null values for the joined columns.
  • Right Join: Similar to a left join, but it includes all rows from the right table and matching rows from the left table. Unmatched rows in the left table will have null values.
  • Full Join: This combines all rows from both tables, regardless of whether there’s a match in the join condition. Unmatched rows will have null values in the corresponding columns.

What is the difference between Primary and Foreign key?

Both primary keys and foreign keys are crucial for maintaining data integrity and relationships within relational databases, but they serve distinct purposes:

Primary Key:

  • Uniqueness: Ensures each row in a table has a unique identifier. This prevents duplicate records and allows for efficient data retrieval.
  • Single Key: A table can only have one primary key. It’s typically composed of one or more columns that uniquely identify a row.
  • Not Null: Primary key columns generally don’t allow null values. This guarantees that every row has a distinct identifier.
  • Example: In a customers table, the primary key could be a customer_id column, ensuring no two customers have the same ID.

Foreign Key:

  • Relationship Builder: Establishes a link between two tables. It references the primary key of another table (parent table).
  • Multiple Keys: A table can have multiple foreign keys, each referencing a different primary key in other tables.
  • Can be Null: Foreign key columns can allow null values, indicating a record that doesn’t have a corresponding entry in the referenced table (parent table).
  • Example: In an orders table, a customer_id foreign key might reference the primary key (customer_id) of the customers table, linking each order to a specific customer.

What is REST-API?

REST API (or RESTful API) stands for Representational State Transfer API. It’s a popular architectural style for designing web APIs. In short, it defines a set of rules for how APIs communicate using HTTP requests and responses. This allows applications to easily interact with each other in a standardized way, regardless of the programming language used. Imagine it as a universal language for applications to exchange information over the web.

When to use Encapsulation and Abstraction in your project?

Encapsulation and abstraction are fundamental concepts in object-oriented programming (OOP) that promote code reusability, maintainability, and security. Here’s a breakdown of when to use them in your project:


  • Data Hiding and Protection: Use encapsulation when you want to control access to an object’s internal data (attributes). By making attributes private and providing public methods (getters and setters) to access and modify them, you can ensure data integrity and prevent unintended modifications.
  • Example: In a Bank class, you might want to encapsulate the accountBalance attribute to ensure it's only accessed and modified through appropriate methods like deposit and withdraw.


  • Focus on Functionality: Use abstraction to hide the implementation details of a class and expose only the essential functionality through interfaces or abstract classes. This allows users to interact with the object without worrying about the underlying complexities.
  • Example: Consider a Shape interface with methods like calculateArea and draw. Different concrete shapes (like Circle or Square) can implement this interface, providing their specific implementations for these methods. Users can then interact with all shapes using the same interface methods, without needing to know the specifics of each shape's implementation.

In essence:

  • Use encapsulation to protect an object’s internal state and control access to its data.
  • Use abstraction to focus on the “what” (functionality) rather than the “how” (implementation details) of an object.

Explain Lazy Loading and Eager Loading?

Lazy loading and eager loading are two strategies for fetching data in object-relational mapping (ORM) frameworks like Hibernate. They determine when and how related entities (objects) are loaded from the database.

Lazy Loading:

  • Delays Loading: Data is retrieved only when it’s explicitly needed. Imagine a product listing page that displays basic product details (name, price) initially. Lazy loading ensures related information like product descriptions or reviews are loaded only when the user clicks on a specific product.
  • Performance Benefits: By avoiding unnecessary database queries for data that might not be used, lazy loading can improve initial page load times.
  • Potential for Extra Queries: If you do end up needing the related data, lazy loading will trigger additional database queries, which might add some overhead.

Eager Loading:

  • Loads Everything Upfront: All related data is fetched along with the primary object in a single database query. This means all product details (description, reviews) might be loaded on the initial product listing page, even if the user doesn’t view them all.
  • Faster Access to Related Data: Since the data is already available, accessing related information doesn’t require additional database queries, potentially improving performance for scenarios where you need to use most or all of the related data.
  • Potentially Slower Initial Load: Eager loading can lead to slower initial page load times if you’re fetching a lot of data that might not be immediately needed.

When to use these annotation in your project — @GetMapping and @PostMapping?

Here’s a breakdown of when to use @GetMapping and @PostMapping annotations in your Spring MVC projects:


  • Use this annotation for methods that handle HTTP GET requests. These requests are typically used to retrieve data from the server.
  • Common Use Cases:
  • Fetching a list of resources (e.g., /products)
  • Getting details of a specific resource (e.g., /products/{id})
  • Handling searches or filtering requests (e.g., /products?category=electronics)
public class ProductController {

public List<Product> getAllProducts() {
// Logic to retrieve all products from the database


  • Use this annotation for methods that handle HTTP POST requests. These requests are typically used to submit data to the server for creation or update purposes.
  • Common Use Cases:
  • Creating a new resource (e.g., submitting a new product through a form)
  • Updating an existing resource (e.g., editing product details)
  • Deleting a resource (although DELETE is a more specific method for deletion)
public class ProductController {

public Product createProduct(@RequestBody Product product) {
// Logic to save the new product to the database

Choosing Between GET and POST:

  • In general, use GET for retrieving data and POST for modifying data (creating, updating, or deleting).
  • However, the specific choice might depend on your API design and the semantics of the operation.

What is Exception Handling rule for Method Overriding?

Here are the key rules for exception handling when overriding methods in Java:

Subclasses and Exceptions:

  • Same or Subclass Exception: When a superclass method declares a checked exception, the overriding method in the subclass can declare the same exception or a subclass of that exception. This allows for more specific exception handling in the subclass.
class SuperClass {
public void doSomething() throws IOException {
// ...

class SubClass extends SuperClass {
public void doSomething() throws FileNotFoundException { // Subclass of IOException
// ...

No Checked Exception: If the superclass method doesn’t declare any exceptions (doesn’t throw any checked exceptions), the overriding method in the subclass cannot declare a checked exception. However, it can still declare unchecked exceptions (runtime exceptions).

class SuperClass {
public void doSomething() {
// ...

class SubClass extends SuperClass {
public void doSomething() throws IOException { // Not allowed (superclass doesn't throw IOException)
// ...

Explain Spring MVC flow in detail?

Spring MVC follows the Model-View-Controller (MVC) architectural pattern, which separates application logic, data presentation, and user interaction for better maintainability and testability. Here’s a detailed breakdown of the flow in a Spring MVC application:

1. Client Request:

  • The user interacts with the web application through their browser, initiating an HTTP request (GET, POST, etc.) to a specific URL on the server.

2. DispatcherServlet Intercept:

  • The DispatcherServlet acts as the front controller in Spring MVC. It receives all incoming HTTP requests from the web container (like Tomcat or Jetty).

3. Handler Mapping:

  • The DispatcherServlet consults the HandlerMapping (usually implemented by RequestMappingHandlerMapping) to determine which controller method should handle the incoming request.
  • This mapping is typically defined using annotations like @RequestMapping or @GetMapping on controller methods, specifying the URL patterns they handle.

4. Handler Selection:

  • Based on the request URL and HTTP method, the HandlerMapping identifies the appropriate controller class and method to handle the request.

5. Controller Invocation:

  • The DispatcherServlet creates an instance of the identified controller class (if not already created) using Spring Dependency Injection.
  • It then invokes the corresponding handler method on the controller, passing the request object as an argument.

6. Model Population:

  • Inside the controller method, the business logic is executed. This might involve:
  • Interacting with the model (domain objects) to retrieve or update data (e.g., accessing a database through a service layer).
  • Performing calculations or validations.
  • Populating a model object with the processed data to be used for view rendering.

7. View Resolution:

  • Once the model is populated, the controller needs to choose a view to render the response. It typically uses a ViewResolver (usually implemented by InternalResourceViewResolver or other resolvers) to identify the appropriate view template.
  • The view name is often specified by the controller method using ModelAndView or returning a String representing the view name.

8. View Rendering:

  • The ViewResolver locates the view template based on the chosen view name (usually a JSP or FreeMarker template).
  • The model object is passed to the view engine (like JSP engine or FreeMarker engine) for rendering the final HTML response.
  • The rendered HTML response is then sent back to the client’s browser.

What happens when there is a exception occurs in Finally block?

In Java, when an exception occurs within the finally block of a try-catch block, the behavior is slightly different from exceptions in the try or catch blocks. Here's how it works:

  1. Exception in Try or Catch Block:
  • If an exception occurs in the try block or a catch block, the following happens:
  • The normal flow of execution stops.
  • If a matching catch block is found for the exception type, the code within that catch block is executed. This allows you to handle the exception gracefully.
  • After the catch block finishes, or if no matching catch block is found, any code in the finally block is still executed.
  1. Exception in Finally Block:
  • If an exception occurs within the finally block:
  • The original exception (from the try or catch block, if any) is suppressed. This means the original exception is not propagated to the caller of the method.
  • The exception thrown from the finally block becomes the new exception that is propagated to the caller.

Key Points:

  • The finally block is always executed, regardless of whether an exception occurs in the try or catch block.
  • An exception in the finally block suppresses the original exception.
  • The exception thrown from the finally block becomes the new exception that the caller needs to handle.

Common Use Cases for Finally Block:

  • Releasing resources (closing files, database connections, etc.) to prevent leaks, even if exceptions occur elsewhere.
  • Performing cleanup actions (like closing streams) that should always happen, regardless of exceptions.

What is the Diamond problem in java?

The “diamond problem” in Java refers to a specific issue that arises in multiple inheritance scenarios, particularly in languages that support both single and multiple inheritance. It’s named after the diamond shape that results when class inheritance diagrams are drawn.

  1. Java’s Approach: Java doesn’t support multiple inheritance of classes (where a class can inherit from more than one class). However, Java allows multiple inheritance of interfaces. If a class implements multiple interfaces, and those interfaces have the same method signature, it doesn’t cause ambiguity because interfaces only declare method signatures, leaving it up to the implementing class to define the method bodies.
  2. Diamond Problem in Java Interfaces: While Java doesn’t have the diamond problem with classes, it can occur with interfaces. If a class implements two interfaces, and both interfaces declare a method with the same signature but different default implementations, the implementing class must provide its own implementation of the method to resolve the ambiguity.

Here is how diamond problem will look like,

interface InterfaceA {
default void display() {
System.out.println("Inside InterfaceA");

interface InterfaceB {
default void display() {
System.out.println("Inside InterfaceB");

class MyClass implements InterfaceA, InterfaceB {
// Here, we must provide our own implementation of display to resolve the ambiguity.
public void display() {
InterfaceA.super.display(); // calling InterfaceA's default implementation
InterfaceB.super.display(); // calling InterfaceB's default implementation

How To resolve it?

To resolve the diamond problem in Java interfaces, where a class implements multiple interfaces with conflicting default method implementations, you can follow several approaches:

  1. Override the Method: Provide your own implementation of the method in the implementing class, thus resolving the ambiguity. This approach is suitable when you want to choose one of the default implementations or provide a completely new implementation.
class MyClass implements InterfaceA, InterfaceB {
public void display() {
InterfaceA.super.display(); // or InterfaceB.super.display()

Call Specific Interface’s Method: Call the specific interface’s method directly in your implementation. This approach is useful when you want to utilize both default implementations or choose a specific one dynamically.

class MyClass implements InterfaceA, InterfaceB {
public void display() {
InterfaceA.super.display(); // or InterfaceB.super.display()
// Additional logic if needed

What is Multilevel Inheritance?

In multilevel inheritance, a class inherits properties and methods from another class, which itself inherits from yet another class. This creates a hierarchy of classes where each class inherits from the one above it in the chain.

Here’s a breakdown of multilevel inheritance in Java:


Imagine a family tree:

  • Grandparent Class: Represents the most base class in the hierarchy.
  • Parent Class: Inherits properties and methods from the grandparent class.
  • Child Class: Inherits properties and methods from the parent class.

Inheritance Chain:

The Child class inherits indirectly from the Grandparent class through the Parent class. The Child class has access to all public and protected members (methods and properties) of both the Parent and Grandparent classes.

Difference between String ,Stringbuffer and Stringbuilder?

Note: String is important topic in Beginners level interview

How to create immutable class in java?

Most common question Java dev interview, If you are following me since long i have written its answer multiple time.

What is the Method Overloading and Overriding?

Method overloading and overriding are both concepts in object-oriented programming (OOP) related to methods in classes. They deal with how methods with the same name are handled, but they differ in their context and purpose.

Method Overloading

  • Definition: Method overloading occurs within a single class. It refers to multiple methods in the same class having the same name but different parameter lists (number, order, or type of parameters).
  • Purpose: Method overloading allows you to create methods that perform similar operations but with different inputs or variations.
class Calculator {
public int add(int a, int b) {
return a + b;

public double add(double a, double b) {
return a + b;

In this example, the add method is overloaded. It has two versions: one for adding integers and another for adding doubles. The compiler can identify which add method to call based on the arguments provided.

Method Overriding

  • Definition: Method overriding occurs between classes in an inheritance hierarchy. It refers to a subclass re-defining a method inherited from its parent class. The method has the same name, return type, and parameter list (same signature) as the parent class method.
  • Purpose: Method overriding allows subclasses to provide their own implementation of a method inherited from a parent class, potentially specializing the behavior for the subclass.
  • Example:
class Animal {
public void makeSound() {
System.out.println("Generic animal sound");

class Dog extends Animal {
public void makeSound() {

Here, the makeSound method is overridden in the Dog class. It inherits the method from Animal but provides a specific implementation for dogs (printing "Woof!").

What is the Hierarchy of exception?

Difference between Arraylist and Linkedlist?

Difference between Set and Arraylist?

How to Create Custom exception in spring boot?

What is Java-8 features — Explain stream api and functional interface?

What is Microservice in details?

Thanks for reading

  • 👏 Please clap for the story and follow me 👉
  • 📰 Read more content on my Medium (60 stories on Java Developer interview)

Find my books here: