Java Spring Interview Questions
Java Spring Interview Questions
The purpose of garbage collection is to identify and discard objects that are no longer needed by a
program so that their resources can be reclaimed and reused.
A Java object is subject to garbage collection when it becomes unreachable to the program in which
it is used.
AWT are heavy-weight components. Swings are light-weight components. Hence swing works faster
than AWT.
4. What is an applet?
A: An applet is a Java program that runs in a Web browser. An applet can be a fully functional Java
application because it has the entire Java API at its disposal.
5. What is Spring?
Web module
SOA is a software design principle and an architectural pattern for implementing loosely coupled,
reusable and coarse grained services. You can implement SOA using any protocols such as HTTP,
HTTPS, JMS, SMTP, RMI, IIOP (i.e. EJB uses IIOP), RPC etc. Messages can be in XML or Data Transfer
Objects (DTOs).
What are the differences between both SOAP WebService and RESTful WebService?
A.
The SOAP WS supports both remote procedure call (i.e. RPC) and message oriented middle-
ware (MOM) integration styles. The Restful Web Service supports only RPC integration style.
The SOAP WS is transport protocol neutral. Supports multiple protocols like HTTP(S),
Messaging, TCP, UDP SMTP, etc. The REST is transport protocol specific. Supports only HTTP
or HTTPS protocols.
The SOAP WS permits only XML data format. The REST permits multiple data formats like
XML, JSON data, text, HTML, etc.
SOAP based reads cannot be cached. REST based reads can be cached. Performs and scales
better.
SOAP WS supports both SSL security and WS-security, the REST supports only point-to-point
SSL security. The SSL encrypts the whole message, whether all of it is sensitive or not.
The SOAP has comprehensive support for both ACID based transaction management for
short-lived transactions and compensation based transaction management for long-running
transactions. It also supports two-phase commit across distributed resources. The REST
supports transactions, but it is neither ACID compliant nor can provide two phase commit
across distributed transactional resources as it is limited by its HTTP protocol.
The SOAP has success or retry logic built in and provides end-to-end reliability even through
SOAP intermediaries. REST does not have a standard messaging system, and expects clients
invoking the service to deal with communication failures by retrying.
Q. How would you decide what style of Web Service to use? SOAP WS or REST?
A. In general, a REST based Web service is preferred due to its simplicity, performance, scalability,
and support for multiple data formats. SOAP is favored where service requires comprehensive
support for security and transactional reliability.
What are the different approaches to developing a SOAP based Web service?
A. 2 approaches.
o The contract-first approach, where you define the contract first with XSD and WSDL
and the generate the Java classes from the contract.
o The contract-last approach where you define the Java classes first and then
generate the contract, which is the WSDL file from the Java classes.
Answer:
The BlockingQueue added as a part of Java 7 concurrent APIs is best suited for this design. The
BlockingQueue is created specifically keeping muti-threading environment in mind. It has several
good features that come handy. E.g. it supports operations that wait for the queue to become non-
empty when retrieving an element, and wait for space to become available in the queue when
storing an element.
What is deep-cloning in Java? How will you implement it?
Answer:
When there is a need to clone an object of a class that has multi-leveled aggregated objects, we
need to implement deep-cloning. E.g. An Employee has a Department object, Department has an
HOD object, HOD has a Role object etc.
To implement deep cloning, all level of aggregated classes must implement Cloneable interface and
override clone() method of the Object class.
Does Java Support multiple inheritance?
Ans. No
When will you need to mark a variable as volatile?
Answer:
When a variable is shared between multiple threads and each thread requires its latest value
modified by other threads then such variables needs to be marked as volatile. When you mark a
variable as volatile, the JVM does not allow the threads to keep a copy of this variable in their cache
memory, but the variable remains in the main memory. All the threads need to take the value of the
variable from the main memory only ensuring, every call gets the latest updated value.
What is memory leak in Java? What coding practices will you follow to prevent it?
Answer:
When there are unwanted objects in the memory which garbage collector cannot clean as they are
still referenced, memory leak happens. Because of such a situation, the amount of memory
consumption increases resulting eventually JVM out of memory condition.
Below are some of the suggestions to prevent such conditions happening.
1. Pay attention to Collection classes, such as HashMap, ArrayList, etc., as they are common places to
find memory leaks. When they are declared static, their life time is the same as the life time of the
application.
2. Pay attention to event listeners and callbacks. A memory leak may occur if a listener is registered
but not unregistered when the class is not being used any longer.
3. If a class manages its own memory, the programmer should be alert for memory leaks. Often times
member variables of an object that point to other objects need to be null out.
Q. What happens if RESTFul resources are accessed by multiple clients? Do you need to make it
thread-safe?
Ans: Since a new Resource instance is created for every incoming Request there is no need to make it
thread-safe or add synchronization. Multiple clients can safely access RESTFul resources concurrently.
Q. What are the software components that we must use to build a SOAP server?
XML processor and HTTP Server are mandatory when you want to build SOAP Server. We have to use
some other tools when you deal with different language.
One of a good example of Strategy pattern from JDK itself is a Collections.sort() method
and Comparator interface, which is a strategy interface and defines a strategy for comparing objects.
Because of this pattern, we don't need to modify sort() method (closed for modification) to compare
any object, at the same time we can implement Comparator interface to define new comparing
strategy (open for extension).
2. What is Observer design pattern in Java? When do you use Observer pattern in Java?
This is one of the most common Java design pattern interview questions. Observer pattern is based
upon notification, there are two kinds of object Subject and Observer. Whenever there is change on
subject's state observer will receive notification. See What is Observer design pattern in Java with
real life example for more details.
State design pattern is used to define and manage the state of an object, while Strategy pattern is
used to define a set of an interchangeable algorithm and let's client choose one of them. So Strategy
pattern is a client driven pattern while Object can manage their state itself.
4. What is decorator pattern in Java? Can you give an example of Decorator pattern?
Decorator pattern is another popular Java design pattern question which is common because of its
heavy usage in java.io package. BufferedReader and BufferedWriter are a good example of decorator
pattern in Java. See How to use Decorator pattern in Java for more details.
5. When to use Composite design Pattern in Java? Have you used previously in your project?
This design pattern question is asked on Java interview not just to check familiarity with the
Composite pattern but also, whether a candidate has the real life experience or not.
The Composite pattern is also a core Java design pattern, which allows you to treat both whole and
part object to treat in a similar way. Client code, which deals with a Composite or individual object
doesn't differentiate between them, it is possible because Composite class also implement the same
interface as their individual part.
One of the good examples of the Composite pattern from JDK is JPanel class, which is both
Component and Container. When the paint() method is called on JPanel, it internally
called paint() method of individual components and let them draw themselves.
On the second part of this design pattern interview question, be truthful, if you have used then say
yes, otherwise say that you are familiar with the concept and used it by your own. By the way, always
remember, giving an example from your project creates a better impression.
The key point to mention, while answering this question is that template method should be final, so
that subclass can not override and change steps of the algorithm, but same time individual step
should be abstract, so that child classes can implement them.
9. What is Factory pattern in Java? What is the advantage of using a static factory method to create
an object?
Factory pattern in Java is a creation Java design pattern and favorite on many Java interviews.Factory
pattern used to create an object by providing static factory methods. There are many advantages of
providing factory methods e.g. caching immutable objects, easy to introduce new objects etc.
See What is Factory pattern in Java and benefits for more details.
10. What is the difference between Decorator and Proxy pattern in Java?
Another tricky Java design pattern question and trick here is that both Decorator and Proxy
implements the interface of the object they decorate or encapsulate. As I said, many Java design
pattern can have similar or exactly same structure but they differ in their intent.
Decorator pattern is used to implement functionality on an already created object, while a Proxy
pattern is used for controlling access to an object.
One more difference between Decorator and the Proxy design pattern is that Decorator doesn't
create an object, instead, it get the object in its constructor, while Proxy actually creates objects. You
can also read Head First Analysis and Design to understand the difference between them.
11. When to use Setter and Constructor Injection in Dependency Injection pattern?
Use Setter injection to provide optional dependencies of an object, while use Constructor iInjection
to provide a mandatory dependency of an object, without which it can not work. This question is
related to Dependency Injection design pattern and mostly asked in the context of Spring framework,
which is now become a standard for developing Java application.
Since Spring provides IOC container, it also gives you a way to specify dependencies either by using
setter methods or constructors. You can also take a look my previous post on the same topic.
13. When to use Adapter pattern in Java? Have you used it before in your project?
Use Adapter pattern when you need to make two class work with incompatible interfaces. Adapter
pattern can also be used to encapsulate third party code so that your application only depends upon
Adapter, which can adapt itself when third party code changes or you moved to a different third
party library.
By the way, this Java design pattern question can also be asked by providing an actual scenario. You
can further read Head First Design Pattern to learn more about Adapter pattern and its real world
usage. The book is updated for Java 8 as well so you will learn new, Java 8 way to implement these
old design patterns.
14. Can you write code to implement producer consumer design pattern in Java?
The Producer-consumer design pattern is a concurrency design pattern in Java which can be
implemented using multiple ways. If you are working in Java 5 then its better to use Concurrency util
to implement producer-consumer pattern instead of plain old wait and notify in Java. Here is a good
example of implementing producer consumer problem using BlockingQueue in Java.
At first, this may look conflicting but once you explore the power of polymorphism, you will start
finding patterns which can provide stability and flexibility of this principle.
One of the key examples of this is State and Strategy design pattern, where Context class is closed for
modification and new functionality is provided by writing new code by implementing a new state of
strategy. See this article to know more about Open closed principle.
16. What is Builder design pattern in Java? When do you use Builder pattern?
Builder pattern in Java is another creational design pattern in Java and often asked in Java interviews
because of its specific use when you need to build an object which requires multiple properties some
optional and some mandatory. See When to use Builder pattern in Java for more details
You can further read this list of SOLID design principles for Java programmer to answer this Java
interview question.
Spring overview
1. What is Spring?
Spring is an open source development framework for Enterprise Java. The core features of the Spring
Framework can be used in developing any Java application, but there are extensions for building web
applications on top of the Java EE platform. Spring framework targets to make Java EE development
easier to use and promote good programming practice by enabling a POJO-based programming
model.
2. What are benefits of Spring Framework?
Lightweight: Spring is lightweight when it comes to size and transparency. The basic version
of spring framework is around 2MB.
Inversion of control (IOC): Loose coupling is achieved in Spring, with the Inversion of Control
technique. The objects give their dependencies instead of creating or looking for dependent
objects.
Aspect oriented (AOP): Spring supports Aspect oriented programming and separates
application business logic from system services.
Container: Spring contains and manages the life cycle and configuration of application
objects.
MVC Framework: Spring’s web framework is a well-designed web MVC framework, which
provides a great alternative to web frameworks.
Transaction Management: Spring provides a consistent transaction management interface
that can scale down to a local transaction and scale up to global transactions (JTA).
Exception Handling: Spring provides a convenient API to translate technology-specific
exceptions (thrown by JDBC, Hibernate, or JDO) into consistent, unchecked exceptions.
3. Which are the Spring framework modules?
The basic modules of the Spring framework are :
Core module
Bean module
Context module
Expression Language module
JDBC module
ORM module
OXM module
Java Messaging Service(JMS) module
Transaction module
Web module
Web-Servlet module
Web-Struts module
Web-Portlet module
4. Explain the Core Container (Application context) module
This is the basic Spring module, which provides the fundamental functionality of the Spring
framework. BeanFactory is the heart of any spring-based application. Spring framework was built on
the top of this module, which makes the Spring container.
5. BeanFactory – BeanFactory implementation example
Dependency Injection
18. What is Dependency Injection in Spring?
Dependency Injection, an aspect of Inversion of Control (IoC), is a general concept, and it can be
expressed in many different ways.This concept says that you do not create your objects but describe
how they should be created. You don’t directly connect your components and services together in
code but describe which services are needed by which components in a configuration file. A
container (the IOC container) is then responsible for hooking it all up.
19. What are the different types of IoC (dependency injection)?
Constructor-based dependency injection: Constructor-based DI is accomplished when the
container invokes a class constructor with a number of arguments, each representing a
dependency on other class.
Setter-based dependency injection: Setter-based DI is accomplished by the container calling
setter methods on your beans after invoking a no-argument constructor or no-argument static
factory method to instantiate your bean.
20. Which DI would you suggest Constructor-based or setter-based DI?
You can use both Constructor-based and Setter-based Dependency Injection. The best solution is
using constructor arguments for mandatory dependencies and setters for optional dependencies.
Spring Beans
21. What are Spring beans?
The Spring Beans are Java Objects that form the backbone of a Spring application. They are
instantiated, assembled, and managed by the Spring IoC container. These beans are created with the
configuration metadata that is supplied to the container, for example, in the form of
XML <bean/> definitions.
Beans defined in spring framework are singleton beans. There is an attribute in bean tag
named "singleton" if specified true then bean becomes singleton and if set to false then the bean
becomes a prototype bean. By default it is set to true. So, all the beans in spring framework are by
default singleton beans.
22. What does a Spring Bean definition contain?
A Spring Bean definition contains all configuration metadata which is needed for the container to
know how to create a bean, its lifecycle details and its dependencies.
23. How do you provide configuration metadata to the Spring Container?
There are three important methods to provide configuration metadata to the Spring Container:
XML based configuration file.
Annotation-based configuration
Java-based configuration
24. How do you define the scope of a bean?
When defining a <bean> in Spring, we can also declare a scope for the bean. It can be defined
through the scope attribute in the bean definition. For example, when Spring has to produce a new
bean instance each time one is needed, the bean’s scope attribute to be prototype . On the other
hand, when the same instance of a bean must be returned by Spring every time it is needed, the the
bean scope attribute must be set to singleton .
25. Explain the bean scopes supported by Spring
There are five scoped provided by the Spring Framework supports following five scopes:
In singleton scope, Spring scopes the bean definition to a single instance per Spring IoC
container.
In prototype scope, a single bean definition has any number of object instances.
In request scope, a bean is defined to an HTTP request. This scope is valid only in a web-
aware Spring ApplicationContext.
In session scope, a bean definition is scoped to an HTTP session. This scope is also valid only
in a web-aware Spring ApplicationContext.
In global-session scope, a bean definition is scoped to a global HTTP session. This is also a
case used in a web-aware Spring ApplicationContext.
The default scope of a Spring Bean is Singleton .
26. Are Singleton beans thread safe in Spring Framework?
No, singleton beans are not thread-safe in Spring framework.
27. Explain Bean lifecycle in Spring framework
The spring container finds the bean’s definition from the XML file and instantiates the bean.
Spring populates all of the properties as specified in the bean definition (DI).
If the bean implements BeanNameAware interface, spring passes the bean’s id
to setBeanName() method.
If Bean implements BeanFactoryAware interface, spring passes
the beanfactory to setBeanFactory() method.
If there are any bean BeanPostProcessors associated with the bean, Spring
calls postProcesserBeforeInitialization() method.
If the bean implements IntializingBean , its afterPropertySet() method is called. If the bean
has init method declaration, the specified initialization method is called.
If there are any BeanPostProcessors associated with the bean, their
postProcessAfterInitialization() methods will be called.
If the bean implements DisposableBean , it will call the destroy() method.
28. Which are the important beans lifecycle methods? Can you override them?
There are two important bean lifecycle methods. The first one is setup which is called when the
bean is loaded in to the container. The second method is the teardown method which is called
when the bean is unloaded from the container.
The bean tag has two important attributes ( init-method and destroy-method ) with which you can
define your own custom initialization and destroy methods. There are also the correspondive
annotations( @PostConstruct and @PreDestroy ).
29. What are inner beans in Spring?
When a bean is only used as a property of another bean it can be declared as an inner bean. Spring’s
XML-based configuration metadata provides the use of <bean/> element inside
the <property/> or <constructor-arg/> elements of a bean definition, in order to define the so-
called inner bean. Inner beans are always anonymous and they are always scoped as prototypes.
30. How can you inject a Java Collection in Spring?
Spring offers the following types of collection configuration elements:
The <list> type is used for injecting a list of values, in the case that duplicates are allowed.
The <set> type is used for wiring a set of values but without any duplicates.
The <map> type is used to inject a collection of name-value pairs where name and value
can be of any type.
The <props> type can be used to inject a collection of name-value pairs where the name
and value are both Strings.
31. What is bean wiring?
Wiring, or else bean wiring is the case when beans are combined together within the Spring
container. When wiring beans, the Spring container needs to know what beans are needed and how
the container should use dependency injection to tie them together.
32. What is bean auto wiring?
The Spring container is able to autowire relationships between collaborating beans. This means that
it is possible to automatically let Spring resolve collaborators (other beans) for a bean by inspecting
the contents of the BeanFactory without using <constructor-arg> and <property> elements.
33. Explain different modes of auto wiring?
The autowiring functionality has five modes which can be used to instruct Spring container to use
autowiring for dependency injection:
no: This is default setting. Explicit bean reference should be used for wiring.
byName: When autowiring byName , the Spring container looks at the properties of the
beans on which autowire attribute is set to byName in the XML configuration file. It then tries
to match and wire its properties with the beans defined by the same names in the configuration
file.
byType: When autowiring by datatype , the Spring container looks at the properties of the
beans on which autowire attribute is set to byType in the XML configuration file. It then tries to
match and wire a property if its type matches with exactly one of the beans name in
configuration file. If more than one such beans exist, a fatal exception is thrown.
constructor: This mode is similar to byType , but type applies to constructor arguments. If
there is not exactly one bean of the constructor argument type in the container, a fatal error is
raised.
autodetect: Spring first tries to wire using autowire by constructor, if it does not work, Spring
tries to autowire by byType .
34. Are there limitations with autowiring?
Limitations of autowiring are:
Overriding: You can still specify dependencies using <constructor-
arg> and <property> settings which will always override autowiring.
Primitive data types: You cannot autowire simple properties such as primitives, Strings, and
Classes.
Confusing nature: Autowiring is less exact than explicit wiring, so if possible prefer using
explicit wiring.
35. Can you inject null and empty string values in Spring?
Yes, you can.
Spring Annotations
36. What is Spring Java-Based Configuration? Give some annotation example.
Java based configuration option enables you to write most of your Spring configuration without XML
but with the help of few Java-based annotations.
An example is the @Configuration annotation, that indicates that the class can be used by the
Spring IoC container as a source of bean definitions. Another example is the @Bean annotated
method that will return an object that should be registered as a bean in the Spring application
context.
37. What is Annotation-based container configuration?
An alternative to XML setups is provided by annotation-based configuration which relies on the
bytecode metadata for wiring up components instead of angle-bracket declarations. 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.
38. How do you turn on annotation wiring?
Annotation wiring is not turned on in the Spring container by default. In order to use annotation
based wiring we must enable it in our Spring configuration file by configuring <context:annotation-
config/> element.
39. @Required annotation
This annotation simply indicates that the affected bean property must be populated at configuration
time, through an explicit property value in a bean definition or through autowiring. The container
throws BeanInitializationException if the affected bean property has not been populated.
40. @Autowired annotation
The @Autowired annotation provides more fine-grained control over where and how autowiring
should be accomplished. It can be used to autowire bean on the setter method just
like @Required annotation, on the constructor, on a property or pn methods with arbitrary names
and/or multiple arguments.
41. @Qualifier annotation
When there are more than one beans of the same type and only one is needed to be wired with a
property, the @Qualifier annotation is used along with @Autowired annotation to remove the
confusion by specifying which exact bean will be wired.
JdbcTemplate class provides many convenience methods for doing things such as converting
database data into primitives or objects, executing prepared and callable statements, and providing
custom database error handling.
44. Spring DAO support
The Data Access Object (DAO) support in Spring is aimed at making it easy to work with data access
technologies like JDBC, Hibernate or JDO in a consistent way. This allows us to switch between the
persistence technologies fairly easily and to code without worrying about catching exceptions that
are specific to each technology.
45. What are the ways to access Hibernate by using Spring?
There are two ways to access Hibernate with Spring:
Inversion of Control with a Hibernate Template and Callback.
Extending HibernateDAOSupport and Applying an AOP Interceptor node.
46. ORM’s Spring support
Spring supports the following ORM’s:
Hibernate
iBatis
JPA (Java Persistence API)
TopLink
JDO (Java Data Objects)
OJB
47. How can we integrate Spring and Hibernate using HibernateDaoSupport?
This implementation case ( @AspectJ based implementation) refers to a style of declaring aspects as
regular Java classes annotated with Java 5 annotations.
The Spring Web MVC framework is designed around a DispatcherServlet that handles all the HTTP
requests and responses.
66. WebApplicationContext
The WebApplicationContext is an extension of the plain ApplicationContext that has some extra
features necessary for web applications. It differs from a normal ApplicationContext in that it is
capable of resolving themes, and that it knows which servlet it is associated with.
67. What is Controller in Spring MVC framework?
Controllers provide access to the application behavior that you typically define through a service
interface. Controllers interpret user input and transform it into a model that is represented to the
user by the view. Spring implements a controller in a very abstract way, which enables you to create
a wide variety of controllers.
68. @Controller annotation
The @Controller annotation indicates that a particular class serves the role of a controller. Spring
does not require you to extend any controller base class or reference the Servlet API.
69. @RequestMapping annotation
@RequestMapping annotation is used to map a URL to either an entire class or a particular handler
method.