Spring Framework - Top 50 Questions for Interview In 2019

Spring Framework - Top 50 Questions for Interview In 2019

In this article, you'll see top 50 Spring interview questions which are most likely to be asked by the interviewer. If you are seeking a future in this field, these questions will surely help you to ace the interview.

In this article, you'll see top 50 Spring interview questions which are most likely to be asked by the interviewer. If you are seeking a future in this field, these questions will surely help you to ace the interview.

Are you thinking of pursuing your career in Spring Framework? Are you searching for an appropriate QnA set to prepare for your interviews? Here is a blog on Spring Interview Questions which discusses on top 50 questions with proper explanation and examples. It will definitely help you to ace the interviews. But before starting with the Spring Interview Questions, let’s take a quick look on Spring Framework’s demand and status in the market.

Since it’s release, the Spring Framework has continued to bloom in the market. Spring community is continuously coming up with new things and have spread into a vast ecosystem. Today, it holds the top position in the framework market. Check out the below graph which shows the frameworks most frequently used in the market as on January 2018.

You might ask why is Spring certification so much in demand? Well, the answer is, because it provides a comprehensive programming and configuration model for modern Java-based enterprise applications. It is not concerned with the deployment platform used. A key element of Spring Framework is infrastructural support at the application level. It’s very much unlikely to go out of the market in the near future with more major releases announced.

Before we move any further let us take a look some of the most frequently asked Spring Interview Questions,

Q1. What are the major features in different versions of Spring Framework?

Q2. What is a Spring Framework?

Q3. List the advantages of Spring Framework

Q4. What are the different features of Spring Framework?

Q5. How many modules are there in Spring Framework and what are they?

Q6. What is a Spring configuration file?

Q7. What are the different components of a Spring application?

Q8. What are the various ways of using Spring Framework?

Q9. What is Spring IOC Container?

Q10. What do you mean by Dependency Injection?

Spring Interview Questions

So, here are the Top 50 Spring Interview Questions which are most likely to be asked by the interviewer. If you are seeking a future in this field, these questions will surely help you to ace the interview. For your ease of access, I have categorized the questions under a few topics, namely:

  • General Questions
  • Dependency Injection/ IoC
  • Spring Beans
  • Spring Annotations
  • Spring Data Access
  • Spring AOP
  • Spring MVC

You may watch the webinar recording of Spring Interview Questions where our instructor has shared his experience and expertise that will help you to crack any Spring Interview.

Let’s begin with the first section of Spring interview questions that is the General Questions.

General Questions – Spring Interview Questions

1. What are the major features in different versions of Spring Framework?

2. What is a Spring Framework?

Spring is a powerful open source, application framework created to reduce the complexity of enterprise application development.It is light-weighted and loosely coupled.It has layered architecture, which allows you to select the components to use, while also providing a cohesive framework for J2EE application development.Spring framework is also called the framework of frameworks as it provides support to various other frameworks such as Struts, Hibernate, Tapestry, EJB, JSF etc.### 3. List the advantages of Spring Framework.
Because of Spring Frameworks layered architecture, you can use what you need and leave which you don’t.Spring Framework enables POJO (Plain Old Java Object) Programming which in turn enables continuous integration and testability.JDBC is simplified due to Dependency Injection and Inversion of Control.It is open-source and has no vendor lock-in.### 4. What are the different features of Spring Framework?

Following are some of the major features of Spring Framework :
Lightweight: Spring is lightweight when it comes to size and transparency. Inversion of control (IOC): The objects give their dependencies instead of creating or looking for dependent objects. This is called Inversion Of Control.Aspect oriented Programming (AOP): Aspect oriented programming in Spring supports cohesive development by separating application business logic from system services.**Container: **Spring Framework creates and manages the life cycle and configuration of the application objects.MVC Framework: Spring Framework’s MVC web application framework is highly configurable. Other frameworks can also be used easily instead of Spring MVC Framework.Transaction Management: Generic abstraction layer for transaction management is provided by the Spring Framework. Spring’s transaction support can be also used in container less environments.JDBC Exception Handling: The JDBC abstraction layer of the Spring offers an exception hierarchy, which simplifies the error handling strategy.### 5. How many modules are there in Spring Framework and what are they?

There are around 20 modules which are generalized into Core Container, Data Access/Integration, Web, AOP (Aspect Oriented Programming), Instrumentation and Test.

**Spring Core Container – This layer is basically the core of Spring Framework. **It contains the following modules:1. Spring Core

  1. Spring Bean
  2. SpEL (Spring Expression Language)
  3. Spring Context
    **Data Access/Integration – This layer provides support to interact with the database. It contains the following modules:JDBC (Java DataBase Connectivity)ORM (Object Relational Mapping)OXM (Object XML Mappers)JMS (Java Messaging Service)TransactionWeb – **This layer provides support to create web application. It contains the following modules :1. Web
  4. Web – MVC
  5. Web – Socket
  6. Web – Portlet
    Aspect Oriented Programming (AOP) – In this layer you can use Advices, Pointcuts etc., to decouple the code.**Instrumentation – **This layer provides support to class instrumentation and classloader implementations.**Test – **This layer provides support to testing with JUnit and TestNG.
    Few Miscellaneous modules are given below:
    **Messaging – *This module provides support for STOMP. It also supports an annotation programming model that is used for routing and processing STOMP messages from WebSocket clients. **Aspects – **This module provides support to integration with AspectJ.

6. What is a Spring configuration file?

A Spring configuration file is an XML file. This file mainly contains the classes information. It describes how those classes are configured as well as introduced to each other. The XML configuration files, however, are verbose and more clean. If it’s not planned and written correctly, it becomes very difficult to manage in big projects.

7. What are the different components of a Spring application?

A Spring application, generally consists of following components:
Interface: It defines the functions.Bean class: It contains properties, its setter and getter methods, functions etc.Spring Aspect Oriented Programming (AOP): Provides the functionality of cross-cutting concerns.Bean Configuration File: Contains the information of classes and how to configure them.User program: It uses the function.### 8. What are the various ways of using Spring Framework?

Spring Framework can be used in various ways. They are listed as follows:

  1. As a Full-fledged Spring web application.
  2. As a third-party web framework, using Spring Frameworks middle-tier.
  3. For remote usage.
  4. As Enterprise Java Bean which can wrap existing POJOs (Plain Old Java Objects).

The next section of Spring Interview Questions is on Dependency Injection and IoC container.

Dependency Injection/ IoC Container – Spring Interview Questions

9. What is Spring IOC Container?

At the core of the Spring Framework, lies the Spring container. The container creates the object, wires them together, configures them and manages their complete life cycle. The Spring container makes use of Dependency Injection to manage the components that make up an application. The container receives instructions for which objects to instantiate, configure, and assemble by reading the configuration metadata provided. This metadata can be provided either by XML, Java annotations or Java code.

**10. What do you mean by Dependency Injection? **

In Dependency Injection, you do not have to create your objects but have to describe how they should be created. You don’t connect your components and services together in the code directly, but describe which services are needed by which components in the configuration file. The IoC container will wire them up together.

11. In how many ways can Dependency Injection be done?

In general, dependency injection can be done in three ways, namely :

  • Constructor Injection
  • Setter Injection
  • Interface Injection

In Spring Framework, only constructor and setter injections are used.

12. Differentiate between constructor injection and setter injection.

Constructor Injection vs Setter Injection

13. How many types of IOC containers are there in spring?

BeanFactory: BeanFactory is like a factory class that contains a collection of beans. It instantiates the bean whenever asked for by clients.ApplicationContext: The ApplicationContext interface is built on top of the BeanFactory interface. It provides some extra functionality on top BeanFactory.### 14. Differentiate between BeanFactory and ApplicationContext.

BeanFactory vs ApplicationContext

15. List some of the benefits of IoC.

Some of the benefits of IoC are:
It will minimize the amount of code in your application.It will make your application easy to test because it doesn’t require any singletons or JNDI lookup mechanisms in your unit test cases.It promotes loose coupling with minimal effort and least intrusive mechanism.It supports eager instantiation and lazy loading of the services.
Let’s move on to the next section of Spring Interview Questions, that is Spring Beans Interview Questions.

Spring Beans – Spring Interview Questions

16. Explain Spring Beans?

They are the objects that form the backbone of the user’s application.Beans are managed by the Spring IoC container.They are instantiated, configured, wired and managed by a Spring IoC containerBeans are created with the configuration metadata that the users supply to the container.### 17. How configuration metadata is provided to the Spring container?

Configuration metadata can be provided to Spring container in following ways:
**XML-Based configuration: **In Spring Framework, the dependencies and the services needed by beans are specified in configuration files which are in XML format. These configuration files usually contain a lot of bean definitions and application specific configuration options. They generally start with a bean tag. For example:

<bean id="studentbean" class="org.edureka.firstSpring.StudentBean">
 <property name="name" value="Edureka"></property>

  • Annotation-Based configuration: Instead of using XML to describe a bean wiring, you can configure the bean into the component class itself by using annotations on the relevant class, method, or field declaration. By default, annotation wiring is not turned on in the Spring container. So, you need to enable it in your Spring configuration file before using it. For example:
<!-- bean definitions go here -->

**Java-based configuration: **The key features in Spring Framework’s new Java-configuration support are @Configuration annotated classes and @Bean annotated methods. > @Bean annotation plays the same role as the element. > @Configuration classes allows to define inter-bean dependencies by simply calling other @Bean methods in the same class.
For example:

public class StudentConfig
public StudentBean myStudent()
{ return new StudentBean(); }

18. How many bean scopes are supported by Spring?

The Spring Framework supports five scopes. They are:
**Singleton: **This provides scope for the bean definition to single instance per Spring IoC container.**Prototype: **This provides scope for a single bean definition to have any number of object instances.**Request: **This provides scope for a bean definition to an HTTP-request. **Session: **This provides scope for a bean definition to an HTTP-session. **Global-session: **This provides scope for a bean definition to an Global HTTP-session.
The last three are available only if the users use a web-aware ApplicationContext.

19. What is the Bean life cycle in Spring Bean Factory Container?

Bean life cycle in Spring Bean Factory Container is as follows:
The Spring container instantiates the bean from the bean’s definition in the XML file.Spring populates all of the properties using the dependency injection, as specified in the bean definition.The factory calls setBeanName() by passing the bean’s ID, if the bean implements the BeanNameAware interface.The factory calls setBeanFactory() by passing an instance of itself, if the bean implements the BeanFactoryAware interface.preProcessBeforeInitialization() methods are called if there are any BeanPostProcessors associated with the bean.If an init-method is specified for the bean, then it will be called.Finally, postProcessAfterInitialization() methods will be called if there are any BeanPostProcessors associated with the bean.
To understand it in better way check the below diagram:

20. Explain inner beans in Spring.

A bean can be declared as an inner bean only when it is used as a property of another bean. For defining a bean, the Spring’s XML based configuration metadata provides the use of element inside the or . Inner beans are always anonymous and they are always scoped as prototypes. For example, let’s say we have one Student class having reference of Person class. Here we will be creating only one instance of Person class and use it inside Student.

Here’s a Student class followed by bean configuration file:


public class Student
private Person person;
//Setters and Getters
public class Person
private String name;
private String address;
//Setters and Getters


<bean id=&ldquo;StudentBean" class="com.edureka.Student">
<property name="person">
<!--This is inner bean -->
<bean class="com.edureka.Person">
<property name="name" value=&ldquo;Scott"></property>
<property name="address" value=&ldquo;Bangalore"></property>

21. Define Bean Wiring.

When beans are combined together within the Spring container, it’s called wiring or bean wiring. The Spring container needs to know what beans are needed and how the container should use dependency injection to tie the beans together, while wiring beans.

22. What do you understand by auto wiring and name the different modes of it?

The Spring container is able to autowire relationships between the collaborating beans. That is, it is possible to let Spring resolve collaborators for your bean automatically by inspecting the contents of the BeanFactory.

Different modes of bean auto-wiring are:
no: This is default setting which means no autowiring. Explicit bean reference should be used for wiring.byName: It injects the object dependency according to name of the bean. It matches and wires its properties with the beans defined by the same names in the XML file.**byType: **It injects the object dependency according to type. It matches and wires a property if its type matches with exactly one of the beans name in XML file.**constructor: **It injects the dependency by calling the constructor of the class. It has a large number of parameters.**autodetect: **First the container tries to wire using autowire by constructor, if it can’t then it tries to autowire by byType.### 23. What are the limitations with auto wiring?

Following are some of the limitations you might face with auto wiring:
**Overriding possibility: You can always specify dependencies using and settings which will override autowiring. Primitive data type: **Simple properties such as primitives, Strings and Classes can’t be autowired.**Confusing nature: **Always prefer using explicit wiring because autowiring is less precise.
In the next section, we will discuss on Spring Annotations Interview Questions.

Spring Annotations – Spring Interview Questions

24. What do you mean by Annotation-based container configuration?

Instead of using XML to describe a bean wiring, the developer moves the configuration into the component class itself by using annotations on the relevant class, method, or field declaration. It acts as an alternative to XML setups. For example:

public class AnnotationConfig
public MyDemo myDemo()
 { return new MyDemoImpll(); }

25. How annotation wiring can be turned on in Spring?

By default, Annotation wiring is not turned on in the Spring container. Thus, to use annotation based wiring we must enable it in our Spring configuration file by configuring context:annotation-config/ element. For example:

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context">
<beans &hellip;&hellip;&hellip;&hellip; />

26. What’s the difference between @Component, @Controller, @Repository & @Service annotations in Spring?

@Component: This marks a java class as a bean. It is a generic stereotype for any Spring-managed component. The component-scanning mechanism of spring now can pick it up and pull it into the application context.

@Controller: This marks a class as a Spring Web MVC controller. Beans marked with it are automatically imported into the Dependency Injection container.

@Service: This annotation is a specialization of the component annotation. It doesn’t provide any additional behavior over the @Component annotation. You can use @Service over @Component in service-layer classes as it specifies intent in a better way.

@Repository: This annotation is a specialization of the @Component annotation with similar use and functionality. It provides additional benefits specifically for DAOs. It imports the DAOs into the DI container and** **makes the unchecked exceptions eligible for translation into Spring DataAccessException.

27. What do you understand by @Required annotation?

@Required is applied to bean property setter methods. This annotation simply indicates that the affected bean property must be populated at the configuration time with the help of an explicit property value in a bean definition or with autowiring. If the affected bean property has not been populated, the container will throw BeanInitializationException.

For example:

public class Employee
private String name;
public void setName(String name)
{this.name=name; }
public string getName()
{ return name; }

28. What do you understand by @Autowired annotation?

The @Autowired annotation provides more accurate control over where and how autowiring should be done. This annotation is used to autowire bean on the setter methods, constructor, a property or methods with arbitrary names or multiple arguments. By default, it is a type driven injection.

For Example:

public class Employee
private String name;
public void setName(String name)
{this.name=name; }
public string getName()
{ return name; }

29. What do you understand by @Qualifier annotation?

When you create more than one bean of the same type and want to wire only one of them with a property you can use the @Qualifier annotation along with @Autowired to remove the ambiguity by specifying which exact bean should be wired.

For example, here we have two classes, Employee and EmpAccount respectively. In EmpAccount, using @Qualifier its specified that bean with id emp1 must be wired.


public class Employee
private String name;
public void setName(String name)
{ this.name=name; }
public string getName()
{ return name; }


public class EmpAccount
private Employee emp;
public void showName()
System.out.println(&ldquo;Employee name : &rdquo;+emp.getName);

30. What do you understand by @RequestMapping annotation?

@RequestMapping annotation is used for mapping a particular HTTP request method to a specific class/ method in controller that will be handling the respective request. This annotation can be applied at both levels:

  • **Class level **: Maps the URL of the request
  • Method level: Maps the URL as well as HTTP request method

Next section of Spring Interview Questions is on Data Access.

Data Access – Spring Interview Questions

31. Describe Spring DAO support?

The Data Access Object (DAO) support in Spring makes it easy to work with data access technologies like JDBC, Hibernate or JDO in a consistent way. This allows one to switch between the persistence technologies easily. It also allows you to code without worrying about catching exceptions that are specific to each of these technology.

32. Name the exceptions thrown by the Spring DAO classes.

See the below diagram, it depicts all the Spring DAO classes in the hierarchical order.

33. Which classes are present in spring JDBC API?

Classes present in JDBC API are as follows:

  1. JdbcTemplate
  2. SimpleJdbcTemplate
  3. NamedParameterJdbcTemplate
  4. SimpleJdbcInsert
  5. SimpleJdbcCall

34. What are the ways by which Hibernate can be accessed using Spring?

There are two ways by which we can access Hibernate using Spring:

  1. Inversion of Control with a Hibernate Template and Callback
    Extending HibernateDAOSupport and Applying an AOP Interceptor node### 35. Name the types of transaction management that Spring supports.

Two types of transaction management are supported by Spring. They are:
**Programmatic transaction management: **In this, the transaction is managed with the help of programming. It provides you extreme flexibility, but it is very difficult to maintain.**Declarative transaction management: **In this, the transaction management is separated from the business code. Only annotations or XML based configurations are used to manage the transactions.### 36. What are the different ORM’s supported by Spring?

Different ORM’s supported by Spring are depicted via the below diagram:

The next section of Spring interview questions discusses on Spring AOP Interview Questions.

Aspect Oriented Programming (AOP) – Spring Interview Questions

37. Describe AOP.

Aspect-oriented programming or AOP is a programming technique which allows programmers to modularize crosscutting concerns or behavior that cuts across the typical divisions of responsibility. Examples of cross-cutting concerns can be logging and transaction management. The core of AOP is an aspect. It encapsulates behaviors that can affect multiple classes into reusable modules.

38. What do you mean by Aspect?

Aspect is a modularization of concern which cuts across multiple objects. Transaction management is a good example of a crosscutting concern in J2EE applications. Aspects are implemented using regular classes or regular classes annotated with the @Aspect annotation in Spring Framework.

39. Explain JoinPoint.

A point during the execution of a program is called JoinPoint, such as the execution of a method or the handling of an exception. In Spring AOP, a joinpoint always represents a method execution.

40. What is an Advice?

An Action taken by an aspect at a particular joinpoint is known as an Advice. Spring AOP uses an advice as an interceptor, maintaining a chain of interceptors “around” the join point.

41. What are the different types of Advices?

Different types of Advices in Spring AOP are:
Before: These types of advices execute before the joinpoint methods and are configured using **@Before **annotation mark.**After returning: **These types of advices execute after the joinpoint methods completes executing normally and are configured using @AfterReturning annotation mark.**After throwing: ** These types of advices execute only if joinpoint method exits by throwing an exception and are configured using @AfterThrowing annotation mark.**After (finally): **These types of advices execute after a joinpoint method, regardless of the method’s exit whether normally or exceptional return and are configured using @After annotation mark.**Around: **These types of advices execute before and after a joinpoint and are configured using @Around annotation mark.### 42. Point out the difference between concern and cross-cutting concern in Spring AOP?

The concern is the behavior we want to have in a particular module of an application. It can be defined as a functionality we want to implement.

The cross-cutting concern is a concern which is applicable throughout the application. This affects the entire application. For example, logging, security and data transfer are the concerns needed in almost every module of an application, thus they are the cross-cutting concerns.

43. What are the different AOP implementations?

Different AOP implementations are depicted by the below diagram:

44. What are the difference between Spring AOP and AspectJ AOP?

Spring AOP vs AspectJ AOP

45. What do you mean by Proxy in Spring Framework?

An object which is created after applying advice to a target object is known as a Proxy. In case of client objects the target object and the proxy object are the same.

46. In Spring, what is Weaving?

The process of linking an aspect with other application types or objects to create an advised object is called Weaving. In Spring AOP, weaving is performed at runtime. Refer the below diagram:

The last section of Spring interview questions is on Spring MVC Interview Questions.

MVC (Model-View-Controller) – Spring Interview Questions

47. What do you mean by Spring MVC framework?

The Spring web MVC framework provides model-view-controller architecture and ready to use components that are used to develop flexible and loosely coupled web applications. The MVC pattern helps in separating the different aspects of the application like input logic, business logic and UI logic, while providing a loose coupling between all these elements.

48. Describe DispatcherServlet.

The DispatcherServlet is the core of Spring Web MVC framework. It handles all the HTTP requests and responses. The DispatcherServlet receives the entry of handler mapping from the configuration file and forwards the request to the controller. The controller then returns an object of Model And View. The DispatcherServlet checks the entry of view resolver in the configuration file and calls the specified view component.

49. Explain WebApplicationContext.

The WebApplicationContext is an extension of the plain ApplicationContext. It has some extra features that are necessary for web applications. It differs from a normal ApplicationContext in terms of its capability of resolving themes and in deciding which servlet it is associated with.

50. In Spring MVC framework, what is controller?

Controllers provide access to the application behavior. These behaviors are generally defined through a service interface. Controllers interpret the user input and transform it into a model which is represented to the user by the view. In Spring, controller is implemented in a very abstract way. It also enables you to create a wide variety of controllers.

I hope this set of Spring Interview Questions and Answers will help you in preparing for your interviews. All the best!

Best Java Microservices Interview Questions In 2019

Best Java Microservices Interview Questions In 2019

In this Microservices interview questions article, I have collected the most frequently asked questions by interviewers. These questions are collected after consulting with Microservices Certification Training experts. Let's discuss the best Java Microservices Interview Questions In 2019

Top Microservices Interview Questions

According to Gartner, **microservices **are the new application platform for cloud development. **Microservices **are deployed and managed independently, and once implemented inside containers they have very little interaction with the underlying OS. So, if you are planning to start your career in the **Microservices **and you wish to know the skills related to it, now is the right time to dive in, when the technology is in its nascent state.

In case you have attended any **Microservices interview **in the recent past, do paste those interview questions in the comments section and we’ll answer them ASAP. You can also comment below if you have any **questions **in your mind, which you might face in your Microservices interview.

You may go through this recording of Microservices Interview Questions and **Answers **where our instructor has explained the topics in a detailed manner with examples that will help you to **understand **this concept better.

Q1. List down the advantages of Java Microservices Architecture.

Q2. What do you know about Microservices?

Microservices, aka Microservice Architecture, is an architectural style that structures an application as a collection of small autonomous services, modeled around a **business domain.**In layman terms, you must have seen how bees build their honeycomb by aligning hexagonal wax cells.They initially start with a small section using various materials and continue to build a large beehive out of it.These cells form a pattern resulting in a strong structure which holds together a particular section of the beehive.Here, each cell is independent of the other but it is also correlated with the other cells.This means that damage to one cell does not damage the other cells, so, bees can reconstruct these cells without impacting the complete beehive.

Fig 1: Beehive Representation of Microservices – Microservices Interview Questions

Refer to the above diagram. Here, each hexagonal shape represents an individual service component. Similar to the working of bees, each agile team builds an individual service component with the available frameworks and the chosen technology stack. Just as in a beehive, each service component forms a strong microservice architecture to provide better scalability. Also, issues with each service component can be handled individually by the agile team with no or minimal impact on the entire application.

Q3. What are the features of Microservices?

Fig 3: Features of Microservices – Microservices Interview Questions
Decoupling – Services within a system are largely decoupled. So the application as a whole can be easily built, altered, and scaled
– Microservices are treated as independent components that can be easily replaced and upgradedBusiness Capabilities – Microservices are very simple and focus on a single capabilityAutonomy – Developers and teams can work independently of each other, thus increasing speedContinous Delivery – Allows frequent releases of software, through systematic automation of software creation, testing, and approvalResponsibility – Microservices do not focus on applications as projects. Instead, they treat applications as products for which they are responsibleDecentralized Governance – The focus is on using the right tool for the right job. That means there is no standardized pattern or any technology pattern. Developers have the freedom to choose the best useful tools to solve their problemsAgility – Microservices support agile development. Any new feature can be quickly developed and discarded again## Q4. What are the best practices to design Microservices?

The following are the best practices to design microservices:

**Fig 4: **Best Practices to Design Microservices – Microservices Interview Questions

Q5. How does Microservice Architecture work?

A microservice architecture has the following components:

**Fig 5: **Architecture of Microservices – Microservices Interview Questions
Clients – Different users from various devices send requests.Identity Providers – Authenticates user or clients identities and issues security tokens.API Gateway – Handles client requests.Static Content – Houses all the content of the system.Management – Balances services on nodes and identifies failures.Service Discovery – A guide to find the route of communication between microservices.Content Delivery Networks – Distributed network of proxy servers and their data centers.Remote Service – Enables the remote access information that resides on a network of IT devices.## Q6. What are the pros and cons of Microservice Architecture?

Q7. What is the difference between Monolithic, SOA and Microservices Architecture?

**Fig 6: **Comparison Between Monolithic SOA & Microservices – Microservices Interview Questions
Monolithic Architecture is similar to a big container wherein all the software components of an application are assembled together and tightly packaged.A Service-Oriented Architecture is a collection of services which communicate with each other. The communication can involve either simple data passing or it could involve two or more services coordinating some activity.Microservice Architecture is an architectural style that structures an application as a collection of small autonomous services, modeled around a business domain.## Q8. What are the challenges you face while working Microservice Architectures?

Developing a number of smaller microservices sounds easy, but the challenges often faced while developing them are as follows.
Automate the Components: Difficult to automate because there are a number of smaller components. So for each component, we have to follow the stages of Build, Deploy and, Monitor.Perceptibility: Maintaining a large number of components together becomes difficult to deploy, maintain, monitor and identify problems. It requires great perceptibility around all the components.Configuration Management: Maintaining the configurations for the components across the various environments becomes tough sometimes.Debugging: Difficult to find out each and every service for an error. It is essential to maintain centralized logging and dashboards to debug problems.## Q9. What are the key differences between SOA and Microservices Architecture?

The key differences between SOA and microservices are as follows:

Q10. What are the characteristics of Microservices?

You can list down the characteristics of microservices as follows:

**Fig 7: **Characteristics of Microservices – Microservices Interview Questions

Q11. What is Domain Driven Design?

**Fig 8: **Principles of DDD – Microservices Interview Questions

Q12. Why there is a need for Domain Driven Design (DDD)?

**Fig 9: **Factors Why we need DDD – Microservices Interview Questions

Q13. What is Ubiquitous language?

If you have to define the** Ubiquitous Language (UL)**, then it is a common language used by developers and users of a specific domain through which the domain can be explained easily.

The ubiquitous language has to be crystal clear so that it brings all the team members on the same page and also translates in such a way that a machine can understand.

Q14. What is Cohesion?

The degree to which the elements inside a module belong together is said to be cohesion.

Q15. What is Coupling?

The measure of the strength of the dependencies between components is said to be coupling. A good design is always said to have High Cohesion and** Low Coupling**.

Q16. What is REST/RESTful and what are its uses?

Representational State Transfer (REST)/RESTful web services are an architectural style to help computer systems communicate over the internet. This makes microservices easier to understand and implement.

Microservices can be implemented with or without RESTful APIs, but it’s always easier to build loosely coupled microservices using RESTful APIs.

Q17. What do you know about Spring Boot?

It’s a knows fact that spring has become more and more complex as new functionalities have been added. If you have to start a new spring project, then you have to add build path or add maven dependencies, configure application server, add spring configuration. So everything has to be done from scratch.

Spring Boot is the solution to this problem. Using spring boot you can avoid all the boilerplate code and configurations. So basically consider yourself as if you’re baking a cake spring is like the ingredients that are required to make the cake and spring boot is the complete cake in your hand.

**Fig 10: **Factors of Spring Boot – Microservices Interview Questions

Q18. What is an actuator in Spring boot?

Spring Boot actuator provides restful web services to access the current state of running an application in the production environment. With the help of actuator, you can check various metrics and monitor your application.

Q19. What is Spring Cloud?

According to the official website of Spring Cloud, Spring Cloud provides tools for developers to quickly build some of the common patterns in distributed systems (e.g. configuration management, service discovery, circuit breakers, intelligent routing, leadership election, distributed sessions, cluster state).

Q20. What problems are solved by Spring Cloud?

While developing distributed microservices with Spring Boot we face few issues which are solved by Spring Cloud.
**The complexity associated with distributed systems – **This includes network issues, Latency overhead, Bandwidth issues, security issues.**Ability to handle Service Discovery – **Service discovery allows processes and services in a cluster to find each other and communicate.**Solved redundancy issues – **Redundancy issues often occur in distributed systems.**Load balancing – **Improves the distribution of workloads across multiple computing resources, such as a computer cluster, network links, central processing units.**Reduces performance issues – **Reduces performance issues due to various operational overheads.## Q21. What is the use of WebMvcTest annotation in Spring MVC applications?

WebMvcTest annotation is used for unit testing Spring MVC Applications in cases where the test objective is to just focus on Spring MVC Components. In the snapshot shown above, we want to launch only the ToTestController. All other controllers and mappings will not be launched when this unit test is executed.

Q22. Can you give a gist about Rest and Microservices?


Though you can implement microservices in multiple ways, REST over HTTP is a way to implement Microservices. REST is also used in other applications such as web apps, API design, and MVC applications to serve business data.


Microservices is an architecture wherein all the components of the system are put into individual components, which can be built, deployed, and scaled individually. There are certain principles and best practices of Microservices that help in building a resilient application.

In a nutshell, you can say that REST is a medium to build Microservices.

Q23. What are different types of Tests for Microservices?

While working with microservices, testing becomes quite complex as there are multiple microservices working together. So, tests are divided into different levels.
At the bottom level, we have technology-facing tests like- unit tests and performance tests. These are completely automated.At the middle level, we have tests for exploratory testing like the stress tests and usability tests.At the **top level, **we have acceptance tests that are few in number. These acceptance tests help stakeholders in understanding and verifying software features.## Q24. What do you understand by Distributed Transaction?

Distributed Transaction is any situation where a single event results in the mutation of two or more separate sources of data which cannot be committed atomically. In the world of microservices, it becomes even more complex as each service is a unit of work and most of the time multiple services have to work together to make a business successful.

Q25. What is an Idempotence and where it is used?

Idempotence is the property of being able to do something twice in such a way that the end result will remain the same i.e. as if it had been done once only.

Usage: Idempotence is used at the remote service, or data source so that, when it receives the instruction more than once, it only processes the instruction once.

Q26. What is Bounded Context?

Bounded Context is a central pattern in Domain-Driven Design. It is the focus of DDD’s strategic design section which is all about dealing with large models and teams. DDD deals with large models by dividing them into different Bounded Contexts and being explicit about their inter-relationships.

Q27. What is Two Factor Authentication?

Two-factor authentication enables the second level of authentication to an account log-in process.

**Fig11: **Representation of Two Factor Authentication – Microservices Interview Questions

So suppose a user has to enter only username and password, then that’s considered a single-factor authentication.

Q28. What are the types of credentials of Two Factor Authentication?

The three types of credentials are:

**Fig 12: **Types of Credentials of Two Factor Authentication – Microservices Interview Questions

Q29. What are Client certificates?

A type of digital certificate that is used by client systems to make authenticated requests to a remote server is known as the** client certificate**. Client certificates play a very important role in many mutual authentication designs, providing strong assurances of a requester’s identity.

Q30. What is the use of PACT in Microservices architecture?

**PACT **is an open source tool to allow testing interactions between service providers and consumers in isolation against the contract made so that the reliability of Microservices integration increases.

Usage in Microservices:

Used to implement Consumer Driven Contract in Microservices.Tests the consumer-driven contracts between consumer and provider of a Microservice.## Q31. What is OAuth?

**OAuth **stands for open authorization protocol. This allows accessing the resources of the resource owner by enabling the client applications on HTTP services such as third-party providers Facebook, GitHub, etc. So with this, you can share resources stored on one site with another site without using their credentials.

Q32. What is Conway’s law?

“Any organization that designs a system (defined broadly) will produce a design whose structure is a copy of the organization’s communication structure.” –*** Mel Conway***

**Fig 13: **Representation of Conway’s Law – Microservices Interview Questions

This law basically tries to convey the fact that, in order for a software module to function, the complete team should communicate well. Therefore the structure of a system reflects the social boundaries of the organization(s) that produced it.

Q33. What do you understand by Contract Testing?

According to Martin Flower,** contract test **is a test at the boundary of an external service which verifies that it meets the contract expected by a consuming service.

Also, contract testing does not test the behavior of the service in depth. Rather, it tests that the inputs & outputs of service calls contain required attributes and the response latency, throughput is within allowed limits.

Q34. What is End to End Microservices Testing?

End-to-end testing validates each and every process in the workflow is functioning properly. This ensures that the system works together as a whole and satisfies all requirements.

In layman terms, you can say that end to end testing is a kind of tests where everything is tested after a particular period.

**Fig 14: **Hierarchy of Tests – Microservices Interview Questions

Q35. What is the use of Container in Microservices?

Containers are a good way to manage microservice based application to develop and deploy them individually*.* You can encapsulate your microservice in a container image along with its dependencies, which then can be used to roll on-demand instances of microservice without any additional efforts required.

**Fig 15: **Representation of Containers and How they are used in Microservices – Microservices Interview Questions

Q36. What is DRY in Microservices architecture?

DRY stands for Don’t Repeat Yourself. It basically promotes the concept of reusing the code. This results in developing and sharing the libraries which in turn result in tight coupling.

Q37. What is a Consumer-Driven Contract (CDC)?

This is basically a pattern for developing Microservices so that they can be used by external systems. When we work on microservices, there is a particular provider who builds it and there are one or more consumers who use Microservice.

Generally, providers specify the interfaces in an XML document. But in Consumer Driven Contract, each consumer of service conveys the interface expected from the Provider.

Q38. What is the role of Web, RESTful APIs in Microservices?

A microservice architecture is based on a concept wherein all its services should be able to interact with each other to build a business functionality. So, to achieve this, each microservice must have an interface. This makes the web API a very important enabler of microservices. Being based on the open networking principles of the Web, RESTful APIs provide the most logical model for building interfaces between the various components of a microservice architecture.

Q39. What do you understand by Semantic monitoring in Microservices architecture?

Semantic monitoring, also known as** synthetic monitoring** combines automated tests with monitoring the application in order to detect business failing factors.

Q40. How can we perform Cross-Functional testing?

Cross-functional testing is a verification of non-functional requirements, i.e. those requirements which cannot be implemented like a normal feature.

Q41. How can we eradicate non-determinism in tests?

Non-Deterministic Tests (NDT) are basically unreliable tests. So, sometimes it may happen that they pass and obviously sometimes they may also fail. As and when they fail, they are made to re-run to pass.

Some ways to remove non-determinism from tests are as follows:
QuarantineAsynchronousRemote ServicesIsolationTimeResource leaks## Q42. What is the difference between Mock or Stub?


A dummy object that helps in running the test.Provides fixed behavior under certain conditions which can be hard-coded.Any other behavior of the stub is never tested.
For example, for an empty stack, you can create a stub that just returns true for empty() method. So, this does not care whether there is an element in the stack or not.


A dummy object in which certain properties are set initially.The behavior of this object depends on the set properties.The object’s behavior can also be tested.
For example, for a Customer object, you can mock it by setting name and age. You can set age as 12 and then test for isAdult() method that will return true for age greater than 18. So, your Mock Customer object works for the specified condition.

Q43. What do you know about Mike Cohn’s Test Pyramid?

Mike Cohn provided a model called Test Pyramid. This describes the kind of automated tests required for software development.

**Fig 16: **Mike Cohn’s Test Pyramid – Microservices Interview Questions

As per pyramid, the number of tests at first layer should be highest. At service layer, the number of tests should be less than at the unit test level, but more than at the end-to-end level.

Q44. What is the purpose of Docker?

Docker provides a container environment that can be used to host any application. In this, the software application and the dependencies which support it are tightly-packaged together.

So, this packaged product is called a Container and since it is done by Docker, it is called Docker container!

Q45. What is Canary Releasing?

Canary Releasing is a technique to reduce the risk of introducing a new software version in production. This is done by slowly rolling out the change to a small subset of users before giving it out to the entire infrastructure, i.e. making it available to everybody.

Q46. What do you mean by Continuous Integration (CI)?

Continuous Integration (CI) is the process of automating the build and testing of code every time a team member commits changes to version control. This encourages developers to share code and unit tests by merging the changes into a shared version control repository after every small task completion.

Q47. What is Continuous Monitoring?

**Continuous monitoring **gets into the depth of monitoring coverage, from in-browser front-end performance metrics, through application performance, and down to host virtualized infrastructure metrics.

Q48. What is the role of an architect in Microservices architecture?

An architect in microservices architecture plays the following roles:
Decides broad strokes about the layout of the overall software system.Helps in deciding the zoning of the components. So, they make sure components are mutually cohesive, but not tightly coupled.Code with developers and learn the challenges faced in day-to-day life.Make recommendations for certain tools and technologies to the team developing microservices.Provide technical governance so that the teams in their technical development follow principles of Microservice.## Q49. Can we create State Machines out of Microservices?

As we know that each Microservice owning its own database is an independently deployable program unit, this, in turn, lets us create a State Machine out of it. So, we can specify different states and events for a particular microservice.

For Example, we can define an Order microservice. An Order can have different states. The transitions of Order states can be independent events in the Order microservice.

Q50. What are Reactive Extensions in Microservices?

Reactive Extensions also are known as Rx. It is a design approach in which we collect results by calling multiple services and then compile a combined response. These calls can be synchronous or asynchronous, blocking or non-blocking. Rx is a very popular tool in distributed systems which works opposite to legacy flows.

Hope these Microservices Interview Questions would help you in your Microservices Architect Interviews.

Spring Boot Tutorials - Spring Boot Full Course

Spring Boot Tutorials - Spring Boot Full Course

Spring Boot Tutorials | Full Course - What is Spring? Spring Boot is an open source Java-based framework used to create a Micro Service. Spring Boot contains a comprehensive infrastructure support for developing a micro service and enables you to develop enterprise-ready applications that you can “just run”.

  1. What is Spring ? – 00:05
  2. Dependency Injection? – 05:34
  3. Spring Tool Suite | Spring Boot IDE – 13:40
  4. Spring, Autowire, Dependency Injection – 22:17
  5. Web App using Spring Boot – 40:39
  6. Application Properties File – 55:33
  7. Accepting Client Data – 01:00:11
  8. ModelAndView – 01:08:51
  9. Model Object – 01:16:12
  10. JPA | MVC | H2 Example – 01:20:29
  11. JPA | MVC | H2 Example Part 2 – 01:35:29
  12. Data JPA | MVC | H2 | Query Methods Example – 01:45:12
  13. Data JPA | MVC | H2 | REST Example – 01:54:43
  14. Data JPA | MVC | H2 | REST Example – 02:02:22
  15. Postman | Data JPA | MVC | H2 | REST Example – 02:06:55
  16. Content Negotiation | Data JPA | MVC | H2 | REST – 02:11:29
  17. Spring Boot | MVC | REST Post Example – 2:19:36
  18. Spring Boot | MVC | REST PUT DELETE Example – 02:27:35
  19. Spring Boot Data REST Example – 02:36:30

Spring Boot Tutorials | Full Course:- https://github.com/navinreddy20/Spring-Boot

50+ Java Interview Questions for Programmers

50+ Java Interview Questions for Programmers

This article contains more than 50 Java Interview questions covering all important topics like core Java fundamentals, Java Collection Framework, Java Multithreading and Concurrency, Java IO, JDBC, JVM Internals, Coding Problems, Object-Oriented programming, etc.

This article contains more than 50 Java Interview questions covering all important topics like core Java fundamentals, Java Collection Framework, Java Multithreading and Concurrency, Java IO, JDBC, JVM Internals, Coding Problems, Object-Oriented programming, etc.

Are you ready for your next Java interview?

Hello, guys! Recently, I have been sharing a lot of Java Interview questions and discussion individually, and many of my readers requested to bring them together so that they can have them in the same page and prepare better and this post is the result of that.

This article contains more than 50 Java Interview questions covering all important topics like core Java fundamentals, Java Collection Framework, Java Multithreading and Concurrency, Java IO, JDBC, JVM Internals, Coding ProblemsObject-Oriented programming, etc.

The questions are also picked up from various interviews and they are, by no means, very difficult, and you might have seen them already in your telephonic or face-to-face round of interview.

The questions are also very good to revise important topics like multithreading and collections as I have also shared some useful resources for further learning and improvement like The Complete Java MasterClass to brush up and fill gaps in your Java skills.

So what are we waiting for here is the list of some of the frequently asked Java questions from interviews from both beginner and experienced Java developer of 2 to 5 years experience:

Java Interview Questions and Answers
  1. How Java achieves platform independence? (answer)
  2. hint: bytecode and Java Virtual Machine
  3. What is **ClassLoader** in Java? (answer)
  4. hint: part of JVM that loads bytecodes for classes. You can write your own.
  5. Write a Java program to check if a number is Even or Odd? (answer)
  6. hint: you can use bitwise operator, e.g. bitwise AND &, remember, even the number has zero at the end in binary format and an odd number has 1 in the end.
  7. Difference between **ArrayList** and **HashSet** in Java? (answer)
  8. hint: all differences between List and Set are applicable here, e.g. ordering, duplicates, random search, etc.
  9. What is double checked locking in Singleton? (answer)
  10. hint: two-time check whether instances is initialized or not, first without locking and second with locking.

6) How do you create thread-safe Singleton in Java? (answer)

hint: many ways, e.g. using Enum or by using double-checked locking pattern or using a nested static class.

7) When to use volatile variable in Java? (answer)

hint: when you need to instruct the JVM that a variable can be modified by multiple threads and give hint to JVM that does not cache its value.

8) When to use a transient variable in Java? (answer)

hint: when you want to make a variable non-serializable in a class, which implements the Serializable interface. In other words, you can use it for a variable whose value you don’t want to save. See The Complete Java MasterClass to learn about transient variables in Java.

9) Difference between the transient and volatile variable in Java? (answer)

hint: totally different, one used in the context of serialization while the other is used in concurrency.

10) Difference between Serializable and Externalizable in Java? (answer)

hint: Externalizable gives you more control over the Serialization process.

11) Can we override the private method in Java? (answer)

hint: No, because it’s not visible in the subclass, a primary requirement for overriding a method in Java.

12) Difference between **Hashtable** and **HashMap** in Java? (answer)

hint: several but most important is Hashtable, which is synchronized, while HashMap is not. It’s also legacy and slow as compared to HashMap.

13) Difference between **List**and **Set**in Java? (answer)

hint: List is ordered and allows duplicate. Set is unordered and doesn’t allow duplicate elements.

14) Difference between **ArrayList** and **Vector** in Java (answer)

hint: Many, but most important is that ArrayList is non-synchronized and fast while Vector is synchronized and slow. It’s also legacy class like Hashtable.

15) Difference between **Hashtable** and **ConcurrentHashMap** in Java? (answer)

hint: more scalable

16) How does **ConcurrentHashMap** achieve scalability? (answer)

hint: by dividing the map into segments and only locking during the write operation.

17) Which two methods you will override for an **Object** to be used as **Key** in **HashMap**? (answer)

hint: equals and hashcode

18) Difference between wait and sleep in Java? (answer)

hint: The wait() method releases the lock or monitor, while sleep doesn’t.

19) Difference between **notify** and **notifyAll** in Java? (answer)

hint: notify notifies one random thread is waiting for that lock while notifyAll inform to all threads waiting for a monitor. If you are certain that only one thread is waiting then use notify, or else notifyAll is better. See Threading Essentials Mini-Course by Java Champion Heinz Kabutz to learn more about threading basics.

20) Why you override hashcode, along with **equals()** in Java? (answer)

hint: to be compliant with equals and hashcode contract, which is required if you are planning to store your object into collection classes, e.g. HashMap or ArrayList.

21) What is the load factor of **HashMap** means? (answer)

hint: The threshold that triggers the re-sizing of HashMap is generally 0.75, which means HashMap resize itself if it’s 75 percent full.

22) Difference between **ArrayList** and **LinkedList** in Java? (answer)

hint: same as an array and linked list, one allows random search while other doesn’t. Insertion and deletion easy on the linked list but a search is easy on an array. See Java Fundamentals: Collections Richard Warburton course on Pluralsight to learn more about essential Collection data structure in Java.

23) Difference between **CountDownLatch** and **CyclicBarrier** in Java? (answer)

hint: You can reuse CyclicBarrier after the barrier is broken but you cannot reuse CountDownLatch  after the count reaches to zero.

24) When do you use **Runnable** vs **Thread** in Java? (answer)

hint: always

25) What is the meaning of Enum being type-safe in Java? (answer)

hint: It means you cannot assign an instance of different Enum type to an Enum variable. e.g. if you have a variable like DayOfWeek day then you cannot assign it value from DayOfMonth enum.

26) How does Autoboxing of Integer work in Java? (answer)

hint: using valueOf() method

27) Difference between **PATH** and **Classpath** in Java? (answer)

hint: PATH is used by the operating system while Classpath is used by JVM to locate Java binary, e.g. JAR files or Class files. See Java Fundamentals: The Core Platform to learn more about PATHClasspath, and other Java environment variable.

28) Difference between method overloading and overriding in Java? (answer)

hint: Overriding happens at subclass while overloading happens in the same class. Also, overriding is a runtime activity while overloading is resolved at compile time.

29) How do you prevent a class from being sub-classed in Java? (answer)

hint: just make its constructor private

30) How do you restrict your class from being used by your client? (answer)

hint: make the constructor private or throw an exception from the constructor

31) Difference between **StringBuilder** and **StringBuffer** in Java? (answer)

hint: StringBuilder is not synchronized while StringBuffer is synchronized.

32) Difference between Polymorphism and Inheritance in Java? (answer)

hint: Inheritance allows code reuse and builds the relationship between class, which is required by Polymorphism, which provides dynamic behavior. See Java Fundamentals: Object-Oriented Design to learn more about OOP features.

33) Can we override static method in Java? (answer)

hint: No, because overriding resolves at runtime while static method call is resolved at compile time.

34) Can we access the private method in Java? (answer)

hint: yes, in the same class but not outside the class

35) Difference between interface and abstract class in Java? (answer)

hint: from Java 8, the difference is blurred. However, a Java class can still implement multiple interfaces but can only extend one class.

36) Difference between DOM and SAX parser in Java? (answer)

hint: DOM loads whole XML File in memory while SAX doesn’t. It is an event-based parser and can be used to parse a large file, but DOM is fast and should be preferred for small files.

37) Difference between throw and throws keyword in Java? (answer)

hint: throws declare what exception a method can throw in case of error but throw keyword actually throws an exception. See Java Fundamentals: Exception Handling to learn more about Exception handling in Java.

38) Difference between fail-safe and fail-fast iterators in Java? (answer)

hint: fail-safe doesn’t throw ConcurrentModificationException while fail-fast does whenever they detect an outside change on the underlying collection while iterating over it.

39) Difference between Iterator and Enumeration in Java? (answer)

hint: Iterator also gives you the ability to remove an element while iterating while Enumeration doesn’t allow that.

40) What is **IdentityHashMap** in Java? (answer)

hint: A Map, which uses the == equality operator to check equality instead of the equals() method.

41) What is **String** pool in Java? (answer)

hint: A pool of String literals. Remember it’s moved to heap from perm gen space in JDK 7.

42) Can a **Serializable** class contain a non-serializable field in Java? (answer)

hint: Yes, but you need to make it either static or transient.

43) Difference between this and super in Java? (answer)

hint: this refers to the current instance while super refers to an instance of the superclass.

44) Difference between **Comparator** and **Comparable** in Java? (answer)

hint: Comparator defines custom ordering while Comparable defines the natural order of objects, e.g. the alphabetic order for String. See The Complete Java MasterClass to learn more about sorting in Java.

45) Difference between **java.util.Date** and **java.sql.Date** in Java? (answer)

hint: former contains both date and time while later contains only date part.

46) Why wait and notify method are declared in **Object** class in Java? (answer)

hint: because they require lock which is only available to an object.

47) Why Java doesn’t support multiple inheritances? (answer)

hint: It doesn’t support because of bad experience with C++, but with Java 8, it does in some sense — only multiple inheritances of Type are not supported in Java now.

48) Difference between checked and unchecked Exception in Java? (answer)

hint: In case of checked, you must handle exception using catch block, while in case of unchecked, it’s up to you; compile will not bother you.

49) Difference between Error and Exception in Java? (answer)

hint: I am tired of typing please check the answer

50) Difference between race condition and deadlock in Java? (answer)

hint: both are errors that occur in a concurrent application, one occurs because of thread scheduling while others occur because of poor coding.