0% found this document useful (0 votes)
7 views

Spring Interview questions

The document outlines key differences between various Java concepts such as Interface vs Abstract Class, final vs finally vs finalize, and ArrayList vs Vector, among others. It also provides an overview of the Spring Framework, its architecture, and concepts like Inversion of Control (IoC) and Dependency Injection. Additionally, it discusses the advantages of Spring, including loose coupling, ease of testing, and predefined templates.

Uploaded by

Dhandapani R
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Spring Interview questions

The document outlines key differences between various Java concepts such as Interface vs Abstract Class, final vs finally vs finalize, and ArrayList vs Vector, among others. It also provides an overview of the Spring Framework, its architecture, and concepts like Inversion of Control (IoC) and Dependency Injection. Additionally, it discusses the advantages of Spring, including loose coupling, ease of testing, and predefined templates.

Uploaded by

Dhandapani R
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

Java Basic Interview questions:

Diff BW Interface vs Abstract class

Interface Abstract class


Interface can have only abstract methods Abstract class can have abstract and non-abstract methods
Variables declared in a interface are by default final An abstract class may contain non-final variables
Interface has only static and final variables. Abstract class can have final, non-final, static and non-static
variables.
Interface can’t provide the implementation of abstract Abstract class can provide the implementation of interface
class.
A Java interface can be implemented using keyword abstract class can be extended using keyword “extends”.
“implements”
An interface can extend another Java interface only an abstract class can extend another Java class and implement
multiple Java interfaces.
Members of a Java interface are public by default A Java abstract class can have class members like private,
protected, etc.

Diff BW final Vs finally Vs finalize

final finally finalize


Finally is used to place
Final is used to apply restrictions on class, Finalize is used to perform
important code, it will be
method and variable. Final class can't be inherited, clean up processing just
executed whether
final method can't be overridden and final variable before object is garbage
exception is handled or
value can't be changed. collected.
not.

Final is a keyword. Finally is a block. Finalize is a method.

Diff BW ArrayList Vs Vector


ArrayList Vector
ArrayList is not synchronized Vector is synchronized
ArrayList increments 50% of current array Vector increments 100% means doubles the array size if total number of
size if number of element exceeds from its element exceeds than its capacity.
capacity.
ArrayList is fast because it is non- Vector is slow because it is synchronized i.e. in multithreading
synchronized. environment, it will hold the other threads in runnable or non-runnable
state until current thread releases the lock of object.
ArrayList uses Iterator interface to Vector uses Enumeration interface to traverse the elements. But it can
traverse the elements. use Iterator also.

Diff BW ArrayList and LinkedList

ArrayList LinkedList
1) ArrayList internally uses dynamic array to store the LinkedList internally uses doubly linked list to store
elements. the elements.

2) Manipulation with ArrayList is slow because it Manipulation with LinkedList is faster than ArrayList
internally uses array. If any element is removed from because it uses doubly linked list so no bit shifting is
the array, all the bits are shifted in memory. required in memory.
3) ArrayList class can act as a list only because it LinkedList class can act as a list and queue both
implements List only. because it implements List and Deque interfaces.

4) ArrayList is better for storing and accessing data. LinkedList is better for manipulating data.

Diff BW HashMap Vs HashTable

HashMap HashTable
HashMap is not synchronized and therefore it is not thread HashTable is internally synchronized and therefore it is
safe. thread safe.
HashMap allows maximum one null key and any number HashTable doesn’t allow null keys and null values.
of null values.
Iterators returned by the HashMap are fail-fast in nature. Enumeration returned by the HashTable are fail-safe in
nature.
HashMap extends AbstractMap class. HashTable extends Dictionary class.
HashMap returns only iterators to traverse. HashTable returns both Iterator as well as Enumeration for
traversal.
HashMap is fast. HashTable is slow.
HashMap is not a legacy class. HashTable is a legacy class.
HashMap is preferred in single threaded applications. If Although HashTable is there to use in multi threaded
you want to use HashMap in multi threaded application, applications, now a days it is not at all preferred. Because,
wrap it using Collections.synchronizedMap() method. ConcurrentHashMap is better option than HashTable.

Similarities Between HashMap And HashTable In Java :


1) Both store the data in the form of key-value pairs.

2) Both use Hashing technique to store the key-value pairs.

3) Both implement Map interface.

4) Both doesn’t maintain any order for elements.

5) Both give constant time performance for insertion and retrieval operations.

HashMap vs HashSet In Java :


HashSet HashMap
HashSet implements Set interface. HashMap implements Map interface.
HashSet stores the data as objects. HashMap stores the data as key-value pairs.
HashSet internally uses HashMap. HashMap internally uses an array of Entry<K, V>objects.
HashMap doesn’t allow duplicate keys, but allows duplicate
HashSet doesn’t allow duplicate elements.
values.
HashSet allows only one null element. HashMap allows one null key and multiple null values.
Insertion operation requires only one object. Insertion operation requires two objects, key and value.
HashSet is slightly slower than HashMap. HashMap is slightly faster than HashSet.
Similarities Between HashMap And HashSet In Java :
1) Both data structures don’t maintain any order for the elements.

2) Both usehashCode()andequals()method to maintain the uniqueness of the data.

3) The iterators returned by both are fail-fast in nature.


4) Both give constant time performance for insertion and removal operations.

5) Both are not synchronized.

Diff BW HashSet Vs LinkedHashSet vs TreeSet

HashSet LinkedHashSet TreeSet


How they It uses HashMap It uses LinkedHashMap internally to It uses TreeMap internally to store it’s
work internally to store it’s store it’s elements. elements.
internally? elements.
Order Of doesn’t maintain any maintains insertion order of orders the elements according to
Elements order of elements. elements. i.e elements are placed as supplied Comparator. If no
they are inserted. comparator is supplied, elements will
be placed in their natural ascending
order
Performance better performance between HashSet and TreeSet. It’s gives less performance than the
than the performance is almost similar to HashSet and LinkedHashSet as it has
LinkedHashSet and HashSet. But slightly in the slower to sort the elements after each
TreeSet. side as it also maintains LinkedList insertion and removal operations
internally to maintain the insertion
order of elements.
Insertion, performance of order performance of order O(1) for performance of order O(log(n)) for
Removal And O(1) for insertion, insertion, removal and retrieval insertion, removal and retrieval
Retrieval removal and retrieval operations. operations.
Operations operations.
How they It uses equals() and It also uses equals() and hashCode() TreeSet uses compare() or
compare the hashCode() methods to methods to compare the elements. compareTo() methods to compare the
elements? compare the elements elements and thus removing the
and thus removing the possible duplicate elements. It doesn’t
possible duplicate use equals() and hashCode() methods
elements. for comparision of elements.
Null elements allows maximum one allows maximum one null element. TreeSet doesn’t allow even a single
null element. null element. If you try to insert null
element into TreeSet, it throws
NullPointerException.
Memory HashSet requires less LinkedHashSet requires more TreeSet also requires more memory
Occupation memory than memory than HashSet as it also than HashSet as it also maintains
LinkedHashSet and maintains LinkedList along with Comparator to sort the elements along
TreeSet as it uses only HashMap to store its elements with the TreeMap.
HashMap internally to
store its elements.
When To Use? Use HashSet if you Use LinkedHashSet if you want to Use TreeSet if you want to sort the
don’t want to maintain maintain insertion order of elements. elements according to some
any order of elements. Comparator.

Fail Fast Vs Fail Safe Iterators In Java :

Fail-Fast Iterators Fail-Safe Iterators


Fail-Fast iterators doesn’t allow modifications of a collection Fail-Safe iterators allow modifications of a
while iterating over it. collection while iterating over it.
These iterators throwConcurrentModificationExceptionif a These iterators don’t throw any exceptionsif a
collection is modified while iterating over it. collection is modifiedwhile iterating over it.
They use original collection to traverse over the elements of They use copy of the original collection to
the collection. traverse over the elements of the collection.
These iterators require extra memory to clone
These iterators don’t require extra memory.
the collection.
Ex : Iterators returned byArrayList,Vector,HashMap. Ex : Iterator returned byConcurrentHashMap.

Enumeration Vs Iterator In Java :


Enumeration Iterator
UsingEnumeration, you can only traverse UsingIterator, you can remove an element of the collection while
the collection. You can’t do any traversing it.
modifications to collection while traversing
it.
Enumerationis introduced in JDK 1.0 Iteratoris introduced fromJDK 1.2
Enumerationis used to traverse the legacy Iteratoris used to iterate most of the classes in the collection
classes likeVector,StackandHashTable. framework likeArrayList,HashSet,HashMap,LinkedListetc.
Methods :hasMoreElements()andnextEleme
Methods :hasNext(),next()andremove()
nt()
Enumerationis fail-safe in nature. Iteratoris fail-fast in nature.
Enumerationis not safe and secured due to
Iteratoris safer and secured thanEnumeration.
it’s fail-safe nature.

Spring Framework
Spring is a lightweight framework. It can be thought of as a framework of frameworks because it provides
support to various frameworks such as Struts, Hibernate, Tapestry, EJB, JSF etc.

The Spring framework comprises several modules such as IOC, AOP, DAO, Context, ORM, WEB MVC etc.

IOC and Dependency Injection

These are the design patterns that are used to remove dependency from the programming code. They make the code
easier to test and maintain.

The IoC container is responsible to instantiate (to instantiate the application class), configure(to configure the
object) and assemble(to assemble the dependencies between the objects) the objects. The IoC container gets
informations from the XML file and works accordingly.

IOC makes the code loosely coupled. In such case, there is no need to modify the code if our logic is moved to new
environment.
IOC container is responsible to inject the dependency. We provide metadata to the IOC container either by XML file
or annotation on configuration classes.

Advantage of Dependency Injection


makes the code easy to test

makes the code loosely coupled so easy to maintain

Advantages of Spring Framework

1) Predefined Templates
Spring framework provides templates for JDBC, Hibernate, JPA etc. technologies. So there is no need to write too
much code. It hides the basic steps of these technologies.

Let's take the example of JdbcTemplate, you don't need to write the code for exception handling, creating
connection, creating statement, committing transaction, closing connection etc. You need to write the code of
executing query only. Thus, it save a lot of JDBC code.

2) Loose Coupling
The Spring applications are loosely coupled because of dependency injection.

3) Easy to test
The Dependency Injection makes easier to test the application. The EJB or Struts application require server to run the
application but Spring framework doesn't require server.
4) Lightweight
Spring framework is lightweight because of its POJO implementation. The Spring Framework doesn't force the
programmer to inherit any class or implement any interface. That is why it is said non-invasive.

5) Fast Development
The Dependency Injection feature of Spring Framework and it support to various frameworks makes the easy
development of JavaEE application.

6) Powerful abstraction
It provides powerful abstraction to JavaEE specifications such as JMS, JDBC, JPA and JTA.

7) Declarative support
It provides declarative support for caching, validation, transactions and formatting.

Spring Framework Architecture

The Spring framework comprises of many modules such as core, beans, context, expression language, AOP, Aspects,
Instrumentation, JDBC, ORM, OXM, JMS, Transaction, Web, Servlet, Struts etc. These modules are grouped into
Test, Core Container, AOP, Aspects, Instrumentation, Data Access / Integration, Web (MVC / Remoting) .

TEST

This layer provides support of testing with JUnit and TestNG.

Spring Core Container


The Spring Core container contains core, beans, context and expression language (EL) modules.

Core and Beans


These modules provide IOC and Dependency Injection features.

Context
This module supports internationalization (I18N), EJB, JMS, Basic Remoting.

Expression Language
It is an extension to the EL defined in JSP. It provides support to setting and getting property values, method invocation,
accessing collections and indexers, named variables, logical and arithmetic operators, retrieval of objects by name etc

AOP, Aspects and Instrumentation


These modules support aspect oriented programming implementation where you can use Advices, Pointcuts etc. to
decouple the code.

The aspects module provides support to integration with AspectJ.

The instrumentation module provides support to class instrumentation and classloader implementations.

Data Access / Integration


This group comprises of JDBC, ORM, OXM, JMS and Transaction modules. These modules basically provide support
to interact with the database.

Web
This group comprises of Web, Web-Servlet, Web-Struts and Web-Portlet. These modules provide support to create web
application.

1.What is Loose Coupling?

 Easy to maintain and modify. By breaking your system into group of reusable objects or codes.

 Spring framework to act as a central module to manage all the object dependencies easily and efficiently.

 Spring Dependency Injection (DI) – Just change in Context xml bean property .

2.What is IOC (Inversion of Control)?

Please Refer page 1 for more details

Responsible of IOC

 to instantiate the application class

 Identify(Find) beans

 Wire Dependencies (to assemble the dependencies between the objects)

 Manage Life Cycle of Bean

There are two types of IoC containers. They are:

1.BeanFactory

2.ApplicationContext

3.What is Dependency Injection?

Is is the process where Spring frameworks looks for beans ,

 it start Searche dependency for beans

 identify the dependency (appropriate bean)

 instantitate the bean and autowire then in neccessary declared place

The Dependency Injection is a design pattern that removes the dependency of the programs or codes. In such case
we provide the information from the external source such as XML file. It makes our code loosely coupled and easier
for testing.
Two ways to perform Dependency Injection in Spring framework
Spring framework provides two ways to inject dependency

By Constructor

By Setter method

4.What is Auto Wiring?

Auto Wiring enables you to inject the object dependency implicitly. It internally uses setter or constructor injection.

Autowiring can't be used to inject primitive and string values. It works with reference only.

Advantage of Autowiring

It requires the less code because we don't need to write the code to inject the dependency explicitly

Disadvantage of Autowiring
No control of programmer.

It can't be used for primitive and string values.

5.Bean Factory and Application Context?

Two of the most fundamental and important packages in Spring are the org.springframework.beans and
org.springframework.context packages. Code in these packages provides the basis for Spring's Inversion of
Control (alternately called Dependency Injection) features.

These interfaces acts as the IoC container

The ApplicationContext interface is built on top of the BeanFactory interface. It adds some extra functionality than
BeanFactory such as simple integration with Spring's AOP, message resource handling (for I18N), event propagation,
application layer specific context (e.g. WebApplicationContext) for web application. So it is better to use
ApplicationContext than BeanFactory.

BeanFactory

1) Bean instantiation/wiring

Resource resource=new ClassPathResource("applicationContext.xml");

BeanFactory factory=new XmlBeanFactory(resource);

ApplicationContext

1) Bean instantiation/wiring
2) Springs AOP features
3) J2EE Supports
4) message resource handling (for use in internationalization)
5) Event Propagation (publish events to beans that are registered as listeners)

ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

6.How is Spring’s singleton bean different from Gang of Four Singleton Pattern?

Gang of Four Singleton Pattern as having only one instance per ClassLoader whereas Spring Singleton is defined as
one instance of bean per container.

7.Design Patterns Used in Java Spring Framework


Dependency injection/ or IoC (inversion of control) – Is the main principle behind decoupling process that Spring does

Factory – Spring uses factory pattern to create objects of beans using Application Context reference
// Spring uses factory pattern to create instances of the objects
BeanFactory factory = new XmlBeanFactory(new FileSystemResource("spring.xml"));
Triangle triangle = (Triangle) factory.getBean("triangle");
triangle.draw();

Proxy – used heavily in AOP, and remoting.

Singleton – by default, beans defined in spring config file (xml) are only created once. No matter how many calls were
made using getBean() method, it will always have only one bean. This is because, by default all beans in spring are
singletons.
This can be overridden by using Prototype bean scope.Then spring will create a new bean object for every request.

Model View Controller – The advantage with Spring MVC is that your controllers are POJOs as opposed to being
servlets. This makes for easier testing of controllers. One thing to note is that the controller is only required to return a
logical view name, and the view selection is left to a separate ViewResolver. This makes it easier to reuse controllers
for different view technologies.

Front Controller – Spring provides DispatcherServlet to ensure an incoming request gets dispatched to your controllers.

View Helper – Spring has a number of custom JSP tags, and velocity macros, to assist in separating code from
presentation in views.

Template method – used extensively to deal with boilerplate repeated code (such as closing connections cleanly, etc..).
For example JdbcTemplate, JmsTemplate, JpaTemplate.

Bean Lifecycle

life cycle of beans consist of call back methods which can be categorized broadly in two groups:

Post initialization call back methods

Pre destruction call back methods

4 ways for controlling life cycle events of bean:

1. InitializingBean and DisposableBean callback interfaces

2. Other Aware interfaces for specific behavior (are ApplicationContextAware,


ApplicationEventPublisherAware, BeanFactoryAware, BeanNameAware, BeanClassLoaderAware,
BootstrapContextAware, MessageSourceAware, ResourceLoaderAware, ServletConfigAware, ServletContextAware)

3. custom init() and destroy() methods in bean configuration file

4. @PostConstruct and @PreDestroy annotations

InitializingBean and DisposableBean callback interfaces


The org.springframework.beans.factory.InitializingBean interface allows a bean to perform initialization work after all
necessary properties on the bean have been set by the container. The InitializingBean interface specifies a
single method:

void afterPropertiesSet() throws Exception;


This is not a preferrable way to initialize the bean because it tightly couple your bean class with spring container.

Similarly, implementing the org.springframework.beans.factory.DisposableBean interface allows a bean to get a


callback when the container containing it is destroyed. The DisposableBean interface specifies a single method:

void destroy() throws Exception;


Bean Scopes

Scope Description
singleton Scopes a single bean definition to a single object instance per Spring IoC container.
prototype Scopes a single bean definition to any number of object instances.
Scopes a single bean definition to the lifecycle of a single HTTP request; that is each and every HTTP
request request will have its own instance of a bean created off the back of a single bean definition. Only valid in
the context of a web-aware SpringApplicationContext.
Scopes a single bean definition to the lifecycle of a HTTP Session. Only valid in the context of a web-
session
aware SpringApplicationContext.
global Scopes a single bean definition to the lifecycle of a global HTTP Session. Typically only valid when
session used in a portlet context. Only valid in the context of a web-aware Spring ApplicationContext.

MICROSERVICE ARCHITECTURE

You might also like