60 Java and Spring Interview Questions You Must Know
Tags: javascript, java, career, spring
Published: 2019-04-17 03:49:35

---
title: 60 Java and Spring Interview Questions You Must Know
published: true
description: 60 Java and Spring Interview Questions You Must Know
tags: #javascript #java #career #spring
canonical_url: https://www.fullstack.cafe/blog/java-spring-interview-questions
---
![60 Java and Spring Interview Questions You Must Know](https://images.pexels.com/photos/747964/pexels-photo-747964.jpeg?auto=compress&cs=tinysrgb&dpr=2&w=350)
A good Java and Spring developer is aways in demand. According to Indeed, there’s currently 29,694 job openings for Java developers and 16,085 for .Net software engineers throughout the US. Follow along and read about latest top Java and Spring Interview Questions.

> 🔴 Originally published on [FullStack.Cafe - Kill Your Tech & Coding Interview](https://www.fullstack.cafe/?utm_source=dev&utm_medium=blog)

### Q1: What is the Difference between JDK and JRE? 
> Topic: **Java**<br/>Difficulty: ⭐

The Java Runtime Environment (JRE) is basically the Java Virtual Machine (JVM) where your Java programs are being executed. It also includes browser plugins for applet execution. The Java Development Kit (JDK) is the full featured Software Development Kit for Java, including the JRE, the compilers and tools (like JavaDoc, and Java Debugger), in order for a user to develop, compile and execute Java applications.

🔗 **Source:** [github.com/snowdream](https://github.com/snowdream/115-Java-Interview-Questions-and-Answers)
### Q2: What is the difference between an Applet and a Java Application?
> Topic: **Java**<br/>Difficulty: ⭐

Applets are executed within a java enabled browser, but a Java application is a standalone Java program that can be executed outside of a browser. However, they both require the existence of a Java Virtual Machine (JVM). Furthermore, a Java application requires a main method with a specific signature, in order to start its execution. Java applets don’t need such a method to start their execution. Finally, Java applets typically use a restrictive security policy, while Java applications usually use more relaxed security policies.

🔗 **Source:** [github.com/snowdream](https://github.com/snowdream/115-Java-Interview-Questions-and-Answers)
### Q3: What is a JSP Page?
> Topic: **Java**<br/>Difficulty: ⭐

A Java Server Page (JSP) is a text document that contains two types of text: static data and JSP elements. Static data can be expressed in any text-based format, such as HTML or XML. JSP is a technology that mixes static content with dynamically-generated content.

🔗 **Source:** [github.com/snowdream](https://github.com/snowdream/115-Java-Interview-Questions-and-Answers)
### Q4: What is a Servlet?
> Topic: **Java**<br/>Difficulty: ⭐

The servlet is a Java programming language class used to process client requests and generate dynamic web content. Servlets are mostly used to process or store data submitted by an HTML form, provide dynamic content and manage state information that does not exist in the stateless HTTP protocol.

🔗 **Source:** [github.com/snowdream](https://github.com/snowdream/115-Java-Interview-Questions-and-Answers)
### Q5: What are pass by reference and pass by value? 
> Topic: **Java**<br/>Difficulty: ⭐⭐

When an object is passed by value, this means that a copy of the object is passed. Thus, even if changes are made to that object, it doesn’t affect the original value. When an object is passed by reference, this means that the actual object is not passed, rather a reference of the object is passed. Thus, any changes made by the external method, are also reflected in all places.

🔗 **Source:** [github.com/snowdream](https://github.com/snowdream/115-Java-Interview-Questions-and-Answers)
### Q6: What are the basic interfaces of Java Collections Framework? 
> Topic: **Java**<br/>Difficulty: ⭐⭐

[Java Collections Framework](http://docs.oracle.com/javase/7/docs/technotes/guides/collections/overview.html) provides a well designed set of interfaces and classes that support operations on a collections of objects. The most basic interfaces that reside in the Java Collections Framework are:

* [Collection](http://docs.oracle.com/javase/7/docs/api/java/util/Collection.html), which represents a group of objects known as its elements.
* [Set](http://docs.oracle.com/javase/7/docs/api/java/util/Set.html), which is a collection that cannot contain duplicate elements.
* [List](http://docs.oracle.com/javase/7/docs/api/java/util/List.html), which is an ordered collection and can contain duplicate elements.
* [Map](http://docs.oracle.com/javase/7/docs/api/java/util/Map.html), which is an object that maps keys to values and cannot contain duplicate keys.

🔗 **Source:** [github.com/snowdream](https://github.com/snowdream/115-Java-Interview-Questions-and-Answers)
### Q7: What differences exist between HashMap and Hashtable? 
> Topic: **Java**<br/>Difficulty: ⭐⭐

Both the [HashMap](http://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html) and [Hashtable](http://docs.oracle.com/javase/7/docs/api/java/util/Hashtable.html) classes implement the Map interface and thus, have very similar characteristics. However, they differ in the following features:

* A [HashMap](http://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html) allows the existence of null keys and values, while a [Hashtable](http://docs.oracle.com/javase/7/docs/api/java/util/Hashtable.html) doesn’t allow neither null keys, nor null values.
* A [Hashtable](http://docs.oracle.com/javase/7/docs/api/java/util/Hashtable.html) is synchronized, while a [HashMap](http://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html) is not. Thus, [HashMap](http://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html) is preferred in single-threaded environments, while a [Hashtable](http://docs.oracle.com/javase/7/docs/api/java/util/Hashtable.html) is suitable for multi-threaded environments.
* A [HashMap](http://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html) provides its set of keys and a Java application can iterate over them. Thus, a [HashMap](http://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html) is fail-fast. On the other hand, a [Hashtable](http://docs.oracle.com/javase/7/docs/api/java/util/Hashtable.html) provides an [Enumeration](http://docs.oracle.com/javase/7/docs/api/java/util/Enumeration.html) of its keys.
* The [Hashtable](http://docs.oracle.com/javase/7/docs/api/java/util/Hashtable.html) class is considered to be a legacy class.

🔗 **Source:** [github.com/snowdream](https://github.com/snowdream/115-Java-Interview-Questions-and-Answers)
### Q8: What does System.gc() and Runtime.gc() methods do?
> Topic: **Java**<br/>Difficulty: ⭐⭐

These methods can be used as a hint to the JVM, in order to start a garbage collection. However, this it is up to the Java Virtual Machine (JVM) to start the garbage collection immediately or later in time.


🔗 **Source:** [github.com/snowdream](https://github.com/snowdream/115-Java-Interview-Questions-and-Answers)
### Q9: What is the difference between Exception and Error in java?
> Topic: **Java**<br/>Difficulty: ⭐⭐

[Exception](http://docs.oracle.com/javase/7/docs/api/java/lang/Exception.html) and [Error](http://docs.oracle.com/javase/7/docs/api/java/lang/Error.html) classes are both subclasses of the [Throwable](http://docs.oracle.com/javase/7/docs/api/java/lang/Throwable.html) class. The [Exception](http://docs.oracle.com/javase/7/docs/api/java/lang/Exception.html)  class is used for exceptional conditions that a user’s program should catch. The [Error](http://docs.oracle.com/javase/7/docs/api/java/lang/Error.html)  class defines exceptions that are not excepted to be caught by the user program.

🔗 **Source:** [github.com/snowdream](https://github.com/snowdream/115-Java-Interview-Questions-and-Answers)
### Q10: What is an Java Applet?
> Topic: **Java**<br/>Difficulty: ⭐⭐

A Java Applet is program that can be included in a HTML page and be executed in a java enabled client browser. Applets are used for creating dynamic and interactive web applications.

🔗 **Source:** [github.com/snowdream](https://github.com/snowdream/115-Java-Interview-Questions-and-Answers)
### Q11: What is JDBC?
> Topic: **Java**<br/>Difficulty: ⭐⭐

JDBC is an abstraction layer that allows users to choose between databases. [JDBC enables developers to write database applications in Java](http://www.javacodegeeks.com/2014/03/java-8-friday-java-8-will-revolutionize-database-access.html), without having to concern themselves with the underlying details of a particular database.

🔗 **Source:** [github.com/snowdream](https://github.com/snowdream/115-Java-Interview-Questions-and-Answers)
### Q12: How are the JSP requests handled?
> Topic: **Java**<br/>Difficulty: ⭐⭐

On the arrival of a JSP request, the browser first requests a page with a .jsp extension. Then, the Web server reads the request and using the JSP compiler, the Web server converts the JSP page into a servlet class. Notice that the JSP file is compiled only on the first request of the page, or if the JSP file has changed.The generated servlet class is invoked, in order to handle the browser’s request. Once the execution of the request is over, the servlet sends a response back to the client. See [how to get Request parameters in a JSP](http://examples.javacodegeeks.com/enterprise-java/jsp/get-request-parameter-in-jsp-page/).

🔗 **Source:** [github.com/snowdream](https://github.com/snowdream/115-Java-Interview-Questions-and-Answers)
### Q13: What are Decalarations?
> Topic: **Java**<br/>Difficulty: ⭐⭐

Declarations are similar to variable declarations in Java. Declarations are used to declare variables for subsequent use in expressions or scriptlets. To add a declaration, you must use the sequences to enclose your declarations.

🔗 **Source:** [github.com/snowdream](https://github.com/snowdream/115-Java-Interview-Questions-and-Answers)
### Q14: What are benefits of using Spring?
> Topic: **Spring**<br/>Difficulty: ⭐⭐

Following is the list of few of the great benefits of using 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 using the technique Inversion of Control. The objects give their dependencies instead of creating or looking for dependent objects.
*   **Aspect oriented (AOP)** − Spring supports Aspect oriented programming and enables cohesive development by separating 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 such as Struts or other over-engineered or less popular web frameworks.
*   **Transaction Management** − Spring provides a consistent transaction management interface that can scale down to a local transaction (using a single database, for example) and scale up to global transactions (using JTA, for example).
*   **Exception Handling** − Spring provides a convenient API to translate technology-specific exceptions (thrown by JDBC, Hibernate, or JDO, for example) into consistent, unchecked exceptions.

🔗 **Source:** [tutorialspoint.com](https://www.tutorialspoint.com/spring/spring_interview_questions.htm)
### Q15: What are Spring beans?
> Topic: **Spring**<br/>Difficulty: ⭐⭐

The objects that form the backbone of your application and that are managed by the Spring IoC container are called **beans**. A bean is an object that is instantiated, assembled, and otherwise managed by a Spring IoC container. These beans are created with the configuration metadata that you supply to the container, for example, in the form of XML `<bean/>` definitions.

🔗 **Source:** [tutorialspoint.com](https://www.tutorialspoint.com/spring/spring_interview_questions.htm)
### Q16: What are ORM's Spring supports?
> Topic: **Spring**<br/>Difficulty: ⭐⭐

Spring supports the following ORM's:

*   Hibernate
*   iBatis
*   JPA (Java Persistence API)
*   TopLink
*   JDO (Java Data Objects)
*   OJB

🔗 **Source:** [tutorialspoint.com](https://www.tutorialspoint.com/spring/spring_interview_questions.htm)
### Q17: What is Spring Security?
> Topic: **Spring**<br/>Difficulty: ⭐⭐

**Spring Security** is a separate module of the Spring framework that focuses on providing authentication and authorization methods in Java applications. It also takes care of most of the common security vulnerabilities such as CSRF attacks.

To use Spring Security in web applications, you can get started with a simple annotation: _@EnableWebSecurity_.

🔗 **Source:** [developersbook.com](http://www.developersbook.com/spring/interview-questions/spring-interview-questions-faqs.php#)
### Q18: What is Circular Queue and why will you use one?
> Topic: **Data Structures**<br/>Difficulty: ⭐⭐⭐

**Circular Queue** is a *linear data structure* in which the operations are performed based on FIFO (First In First Out) principle and the last position is connected back to the first position to make a circle. It is also called *Ring Buffer*. Circular queue avoids the *wastage of space* in a regular queue implementation using arrays.

🔗 **Source:** [programiz.com](https://www.programiz.com/dsa/circular-queue)
### Q19: What does “program to interfaces, not implementations” mean?
> Topic: **Design Patterns**<br/>Difficulty: ⭐⭐⭐

*Coding against interface* means, the client code always holds an Interface object which is supplied by a *factory*. 

Any instance returned by the factory would be of type Interface which any factory candidate class must have implemented. This way the client program is not worried about implementation and the interface signature determines what all operations can be done. 

This approach can be used to change the behavior of a program at run-time. It also helps you to write far better programs from the maintenance point of view.

🔗 **Source:** [tutorialspoint.com](https://www.tutorialspoint.com/design_pattern/design_pattern_interview_questions.htm)
### Q20: What is Observer pattern?
> Topic: **Design Patterns**<br/>Difficulty: ⭐⭐⭐

**Observer pattern**  (also known as *Publish-Subscribe Pattern*) is used when there is one-to-many relationship between objects such as if one object is modified, its dependent objects are to be notified automatically. Observer pattern falls under _behavioral_ pattern category.

An object with a one-to-many relationship with other objects who are interested in its state is called the _subject_ or _publisher_. The _observers_ are notified whenever the state of the _subject_ changes and can act accordingly. The _subject_ can have any number of dependent _observers_ which it notifies, and any number of _observers_ can subscribe to the _subject_ to receive such notifications.

Observer pattern uses two actor classes:
* The Observer (os Subscriber) abstract class provides an `update()` method which will be called by the subject to notify it of the subject’s state change. 
* The Subject (or Publisher) class is also an abstract class and defines four primary methods: `attach()`, `detach()`, `setState()`, and `notify()`



<div class="text-center">
<img src="https://upload.wikimedia.org/wikipedia/commons/0/01/W3sDesign_Observer_Design_Pattern_UML.jpg" class="img-fluid"/>
</div>

🔗 **Source:** [sitepoint.com](https://www.sitepoint.com/understanding-the-observer-pattern/)
### Q21: Can you access non static variable in static context?
> Topic: **Java**<br/>Difficulty: ⭐⭐⭐

A static variable in Java belongs to its class and its value remains the same for all its instances. A static variable is initialized when the class is loaded by the JVM. If your code tries to access a non-static variable, without any instance, the compiler will complain, because those variables are not created yet and they are not associated with any instance.

🔗 **Source:** [github.com/snowdream](https://github.com/snowdream/115-Java-Interview-Questions-and-Answers)
### Q22: Does Java support multiple inheritance? 
> Topic: **Java**<br/>Difficulty: ⭐⭐⭐

No, Java does not support multiple inheritance. Each class is able to extend only on one class, but is able to implement more than one interfaces.

🔗 **Source:** [github.com/snowdream](https://github.com/snowdream/115-Java-Interview-Questions-and-Answers)
### Q23: Explain different ways of creating a thread. Which one would you prefer and why?
> Topic: **Java**<br/>Difficulty: ⭐⭐⭐

There are three ways that can be used in order for a [Thread](http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html) to be created:

* A class may extend the [Thread](http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html) class.
* A class may implement the [Runnable](http://docs.oracle.com/javase/7/docs/api/java/lang/Runnable.html) interface.
* An application can use the [Executor](http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Executor.html) framework, in order to create a thread pool.

The [Runnable](http://docs.oracle.com/javase/7/docs/api/java/lang/Runnable.html) interface is preferred, as it does not require an object to inherit the [Thread](http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html) class. In case your application design requires multiple inheritance, only interfaces can help you. Also, the thread pool is very efficient and can be implemented and used very easily.

🔗 **Source:** [github.com/snowdream](https://github.com/snowdream/115-Java-Interview-Questions-and-Answers)
### Q24: What’s a deadlock? 
> Topic: **Java**<br/>Difficulty: ⭐⭐⭐

A condition that occurs when [two processes are waiting for each other to complete](http://www.javacodegeeks.com/2013/01/java-deadlock-example-how-to-analyze-deadlock-situation.html), before proceeding. The result is that both processes wait endlessly.

🔗 **Source:** [github.com/snowdream](https://github.com/snowdream/115-Java-Interview-Questions-and-Answers)
### Q25: What is difference between fail-fast and fail-safe? 
> Topic: **Java**<br/>Difficulty: ⭐⭐⭐

The [Iterator's](http://docs.oracle.com/javase/7/docs/api/java/util/Iterator.html)  fail-safe property works with the clone of the underlying collection and thus, it is not affected by any modification in the collection. All the collection classes in java.util package are fail-fast, while the collection classes in java.util.concurrent are fail-safe. Fail-fast iterators throw a [ConcurrentModificationException](http://examples.javacodegeeks.com/java-basics/exceptions/java-util-concurrentmodificationexception-how-to-handle-concurrent-modification-exception/), while fail-safe iterator never throws such an exception.

🔗 **Source:** [github.com/snowdream](https://github.com/snowdream/115-Java-Interview-Questions-and-Answers)
### Q26: What is Java Priority Queue?
> Topic: **Java**<br/>Difficulty: ⭐⭐⭐

The [PriorityQueue](http://docs.oracle.com/javase/7/docs/api/java/util/PriorityQueue.html) is an unbounded queue, based on a priority heap and its elements are ordered in their natural order. At the time of its creation, we can provide a Comparator that is responsible for ordering the elements of the [PriorityQueue](http://docs.oracle.com/javase/7/docs/api/java/util/PriorityQueue.html). A [PriorityQueue](http://docs.oracle.com/javase/7/docs/api/java/util/PriorityQueue.html) doesn’t allow null values, those objects that doesn’t provide natural ordering, or those objects that don’t have any comparator associated with them. Finally, the Java [PriorityQueue](http://docs.oracle.com/javase/7/docs/api/java/util/PriorityQueue.html) is not thread-safe and it requires O(log(n)) time for its enqueing and dequeing operations.

🔗 **Source:** [github.com/snowdream](https://github.com/snowdream/115-Java-Interview-Questions-and-Answers)
### Q27: When is the finalize() called? What is the purpose of finalization? 
> Topic: **Java**<br/>Difficulty: ⭐⭐⭐

The finalize method is called by the garbage collector, just before releasing the object’s memory. It is normally advised to release resources held by the object inside the finalize method.

🔗 **Source:** [github.com/snowdream](https://github.com/snowdream/115-Java-Interview-Questions-and-Answers)
### Q28: What is structure of Java Heap?
> Topic: **Java**<br/>Difficulty: ⭐⭐⭐

The JVM has a heap that is the runtime data area from which memory for all class instances and arrays is allocated. It is created at the JVM start-up. Heap memory for objects is reclaimed by an automatic memory management system which is known as a garbage collector. Heap memory consists of live and dead objects. Live objects are accessible by the application and will not be a subject of garbage collection. Dead objects are those which will never be accessible by the application, but have not been collected by the garbage collector yet. Such objects occupy the heap memory space until they are eventually collected by the garbage collector.

🔗 **Source:** [github.com/snowdream](https://github.com/snowdream/115-Java-Interview-Questions-and-Answers)
### Q29: What are the restrictions imposed on Java applets?
> Topic: **Java**<br/>Difficulty: ⭐⭐⭐

Mostly due to security reasons, the following restrictions are imposed on Java applets:

* An applet cannot load libraries or define native methods.
* An applet cannot ordinarily read or write files on the execution host.
* An applet cannot read certain system properties.
* An applet cannot make network connections except to the host that it came from.
* An applet cannot start any program on the host that’s executing it.

🔗 **Source:** [github.com/snowdream](https://github.com/snowdream/115-Java-Interview-Questions-and-Answers)
### Q30: What are Scriptlets?
> Topic: **Java**<br/>Difficulty: ⭐⭐⭐

In Java Server Pages (JSP) technology, a scriptlet is a piece of Java-code embedded in a JSP page. The scriptlet is everything inside the tags. Between these tags, a user can add any valid scriplet.

🔗 **Source:** [github.com/snowdream](https://github.com/snowdream/115-Java-Interview-Questions-and-Answers)
### Q31: State the features of an interface.
> Topic: **OOP**<br/>Difficulty: ⭐⭐⭐

An interface is a template that contains only the signature of methods. The signature of a method consists of the numbers of parameters, the type of parameter (value, reference, or output), and the order of parameters. An interface has no implementation on its own because it contains only the definition of methods without any method body. An interface is defined using the _interface_ keyword. Moreover, you cannot instantiate an interface. The various features of an interface are as follows:  

*   An interface is used to implement multiple inheritance in code. This feature of an interface is quite different from that of abstract classes because a class cannot derive the features of more than one class but can easily implement multiple interfaces.
*   It defines a specific set of methods and their arguments.
*   Variables in interface must be declared as _public_, _static_, and _final_ while methods must be _public_ and _abstract_.
*   A class implementing an interface must implement all of its methods.
*   An interface can derive from more than one interface.

🔗 **Source:** [indiabix.com](https://www.indiabix.com/technical/dotnet/object-oriented-programming/)
### Q32: What does SOLID stand for? What are its principles?
> Topic: **Software Architecture**<br/>Difficulty: ⭐⭐⭐

**S.O.L.I.D** is an acronym for the first five object-oriented design (OOD) principles by Robert C. Martin.

* **S** - *Single-responsiblity principle*. A class should have one and only one reason to change, meaning that a class should have only one job.
* **O** - *Open-closed principle*. Objects or entities should be open for extension, but closed for modification.
* **L** - *Liskov substitution principle*. Let q(x) be a property provable about objects of x of type T. Then q(y) should be provable for objects y of type S where S is a subtype of T.
* **I** - *Interface segregation principle*. A client should never be forced to implement an interface that it doesn't use or clients shouldn't be forced to depend on methods they do not use.
* **D** - *Dependency Inversion Principle*. Entities must depend on abstractions not on concretions. It states that the high level module must not depend on the low level module, but they should depend on abstractions.

🔗 **Source:** [scotch.io](https://scotch.io/bar-talk/s-o-l-i-d-the-first-five-principles-of-object-oriented-design)
### Q33: What are the DRY and DIE principles?
> Topic: **Software Architecture**<br/>Difficulty: ⭐⭐⭐

In software engineering, **Don't Repeat Yourself (DRY)** or **Duplication is Evil (DIE)** is a principle of software development.

🔗 **Source:** [stackoverflow.com](https://en.wikipedia.org/wiki/KISS_principle)
### Q34: Is it better to return NULL or empty values from functions/methods where the return value is not present?
> Topic: **Software Architecture**<br/>Difficulty: ⭐⭐⭐

Returning `null` is usually the best idea if you intend to indicate that no data is available.

An empty object implies data has been returned, whereas returning `null` clearly indicates that nothing has been returned.

Additionally, returning a `null` will result in a null exception if you attempt to access members in the object, which can be useful for highlighting buggy code - attempting to access a member of nothing makes no sense. Accessing members of an empty object will not fail meaning bugs can go undiscovered.

🔗 **Source:** [stackoverflow.com](https://softwareengineering.stackexchange.com/questions/120355/is-it-better-to-return-null-or-empty-values-from-functions-methods-where-the-ret)
### Q35: Explain Bean lifecycle in Spring framework
> Topic: **Spring**<br/>Difficulty: ⭐⭐⭐

Following is sequence of a bean lifecycle in Spring:

*   **Instantiate** − First the spring container finds the bean's definition from the XML file and instantiates the bean..
*   **Populate properties** − Using the dependency injection, spring populates all of the properties as specified in the bean definition.
*   **Set Bean Name** − If the bean implements BeanNameAware interface, spring passes the bean's id to setBeanName() method.
*   **Set Bean factory** − If Bean implements BeanFactoryAware interface, spring passes the beanfactory to setBeanFactory() method.
*   **Pre Initialization** − Also called postprocess of bean. If there are any bean BeanPostProcessors associated with the bean, Spring calls postProcesserBeforeInitialization() method.
*   **Initialize beans** − If the bean implements IntializingBean,its afterPropertySet() method is called. If the bean has init method declaration, the specified initialization method is called.
*   **Post Initialization** − If there are any BeanPostProcessors associated with the bean, their postProcessAfterInitialization() methods will be called.
*   **Ready to use** − Now the bean is ready to use by the application.
*   **Destroy** − If the bean implements DisposableBean , it will call the destroy() method .

🔗 **Source:** [tutorialspoint.com](https://www.tutorialspoint.com/spring/spring_interview_questions.htm)
### Q36: What is Controller in Spring MVC framework?
> Topic: **Spring**<br/>Difficulty: ⭐⭐⭐

**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.

🔗 **Source:** [tutorialspoint.com](https://www.tutorialspoint.com/spring/spring_interview_questions.htm)
### Q37: What is Aspect?
> Topic: **Spring**<br/>Difficulty: ⭐⭐⭐

An **Aspect** is a module which has a set of APIs providing _cross-cutting_ requirements. For example, a logging module would be called AOP aspect for logging. An application can have any number of aspects depending on the requirement. In Spring AOP, aspects are implemented using regular classes (the schema-based approach) or regular classes annotated with the @Aspect annotation (`@AspectJ` style).

🔗 **Source:** [tutorialspoint.com](https://www.tutorialspoint.com/spring/spring_interview_questions.htm)
### Q38: What is the typical Bean life cycle in Spring Bean Factory Container?
> Topic: **Spring**<br/>Difficulty: ⭐⭐⭐

Bean life cycle in Spring Bean Factory Container is as follows:

*   The spring container finds the beans definition from the XML file and instantiates the bean.
    
*   Using the dependency injection, spring populates all of the properties as specified in the bean definition
    
*   If the bean implements the BeanNameAware interface, the factory calls `setBeanName()` passing the beans ID.
    
*   If the bean implements the BeanFactoryAware interface, the factory calls `setBeanFactory()`, passing an instance of itself.
    
*   If there are any BeanPostProcessors associated with the bean, their post- `ProcessBeforeInitialization()` methods will be called.
    
*   If an init-method is specified for the bean, it will be called.
    
*   Finally, if there are any BeanPostProcessors associated with the bean, their `postProcessAfterInitialization()` methods will be called.

🔗 **Source:** [developersbook.com](http://www.developersbook.com/spring/interview-questions/spring-interview-questions-faqs.php#)
### Q39: How to handle exceptions in Spring MVC Framework?
> Topic: **Spring**<br/>Difficulty: ⭐⭐⭐

 Spring MVC Framework provides the following ways to help us achieving robust exception handling.
    
1.  **Controller Based** – We can define exception handler methods in our controller classes. All we need is to annotate these methods with @ExceptionHandler annotation.
2.  **Global Exception Handler** – Exception Handling is a cross-cutting concern and Spring provides @ControllerAdvice annotation that we can use with any class to define our global exception handler.
3.  **HandlerExceptionResolver implementation** – For generic exceptions, most of the times we serve static pages. Spring Framework provides `HandlerExceptionResolver` interface that we can implement to create global exception handler. The reason behind this additional way to define global exception handler is that Spring framework also provides default implementation classes that we can define in our spring bean configuration file to get spring framework exception handling benefits.

🔗 **Source:** [journaldev.com](https://www.journaldev.com/2696/spring-interview-questions-and-answers#spring-best-practices)
### Q40: What is Spring IoC Container?
> Topic: **Spring**<br/>Difficulty: ⭐⭐⭐

 **Inversion of Control** (IoC) is the mechanism to achieve loose-coupling between Objects dependencies. To achieve loose coupling and dynamic binding of the objects at runtime, the objects define their dependencies that are being injected by other assembler objects. Spring IoC container is the program that injects dependencies into an object and makes it ready for our use.
    
Spring Framework IoC container classes are part of `org.springframework.beans` and `org.springframework.context` packages and provides us different ways to decouple the object dependencies.
    
Some of the useful ApplicationContext implementations that we use are;
    
*   `AnnotationConfigApplicationContext`: For standalone java applications using annotations based configuration.
*   `ClassPathXmlApplicationContext`: For standalone java applications using XML based configuration.
*   `FileSystemXmlApplicationContext`: Similar to ClassPathXmlApplicationContext except that the xml configuration file can be loaded from anywhere in the file system.
*   `AnnotationConfigWebApplicationContext` and `XmlWebApplicationContext` for web applications.

🔗 **Source:** [journaldev.com](https://www.journaldev.com/2696/spring-interview-questions-and-answers#spring-best-practices)
### Q41: Is the DispatcherServlet instantiated via an application context?
> Topic: **Spring**<br/>Difficulty: ⭐⭐⭐

No, the `DispatcherServlet` is instantiated by Servlet containers like Tomcat or Jetty. You must define the `DispatcherServlet` into the web.xml file as shown below.

You can see that load-on-startup tag is 1, which means `DispatcherServlet` is instantiated when you deploy the Spring MVC application to Tomcat or any other Servlet container. During instantiation, it looks for a file servlet-name-context.xml and then initializes beans defined in this file.

🔗 **Source:** [dzone.com](https://dzone.com/articles/top-20-spring-mvc-interview-questions-and-answers)
### Q42: What is the purpose of the session scope?
> Topic: **Spring**<br/>Difficulty: ⭐⭐⭐

The purpose of the **session scope** is to create an instance of the bean for an HTTP Session. This means the same bean can serve multiple requests if it is scoped in session. You can define the scope of a Spring bean using scope attribute or the `@Scope` annotation in a Spring MVC application.

🔗 **Source:** [dzone.com](https://dzone.com/articles/top-20-spring-mvc-interview-questions-and-answers)
### Q43: What is the difference between a synchronized method and a synchronized block?
> Topic: **Java**<br/>Difficulty: ⭐⭐⭐⭐

In Java programming, each object has a lock. A thread can acquire the lock for an object by using the synchronized keyword. The synchronized keyword can be applied in a method level (coarse grained lock) or block level of code (fine grained lock).

🔗 **Source:** [github.com/snowdream](https://github.com/snowdream/115-Java-Interview-Questions-and-Answers)
### Q44: How do you ensure that N threads can access N resources without deadlock? 
> Topic: **Java**<br/>Difficulty: ⭐⭐⭐⭐

A very simple way to avoid deadlock while using N threads is to impose an ordering on the locks and force each thread to follow that ordering. Thus, if all threads lock and unlock the mutexes in the same order, no deadlocks can arise.

🔗 **Source:** [github.com/snowdream](https://github.com/snowdream/115-Java-Interview-Questions-and-Answers)
### Q45: What is Perm Gen space in Heap?
> Topic: **Java**<br/>Difficulty: ⭐⭐⭐⭐

Perm Gen stands for permanent generation. It is the space on Java Heap that holds meta-data describing user classes (classes that are not part of the Java language). Examples of such meta-data are objects describing classes and methods and they are stored in the Permanent Generation. Applications with large code-base can quickly fill up this segment of the heap which will cause `java.lang.OutOfMemoryError: PermGen` no matter how high your `-Xmx` (maximum size of the memory allocation pool) and how much memory you have on the machine.

🔗 **Source:** [github.com/snowdream](https://github.com/snowdream/115-Java-Interview-Questions-and-Answers)
### Q46: What is RMI?
> Topic: **Java**<br/>Difficulty: ⭐⭐⭐⭐

The Java Remote Method Invocation (Java RMI) is a Java API that performs the object-oriented equivalent of remote procedure calls (RPC), with support for direct transfer of serialized Java classes and distributed garbage collection. Remote Method Invocation (RMI) can also be seen as the process of activating a method on a remotely running object. RMI offers location transparency because a user feels that a method is executed on a locally running object. 

🔗 **Source:** [github.com/snowdream](https://github.com/snowdream/115-Java-Interview-Questions-and-Answers)
### Q47: Explain different types of inheritance.
> Topic: **OOP**<br/>Difficulty: ⭐⭐⭐⭐

Inheritance in OOP is of four types:  

*   **Single inheritance** - Contains one base class and one derived class
*   **Hierarchical inheritance** - Contains one base class and multiple derived classes of the same base class
*   **Multilevel inheritance** - Contains a class derived from a derived class
*   **Multiple inheritance** - Contains several base classes and a derived class

All .NET languages supports single, hierarchical, and multilevel inheritance. They do not support multiple inheritance because in these languages, a derived class cannot have more than one base class. However, you can implement multiple inheritance in.NET through interfaces.

🔗 **Source:** [indiabix.com](https://www.indiabix.com/technical/dotnet/object-oriented-programming/)
### Q48: What is GOD class and why should we avoid it?
> Topic: **Software Architecture**<br/>Difficulty: ⭐⭐⭐⭐

The most effective way to break applications it to create **GOD** classes. That are classes that keeps track of a lot of information and have several responsibilities. One code change will most likely affect other parts of the class and therefore indirectly all other classes that uses it. That in turn leads to an even bigger maintenance mess since no one dares to do any changes other than adding new functionality to it.

🔗 **Source:** [stackoverflow.com](https://stackoverflow.com/questions/10620022/what-is-an-example-of-the-single-responsibility-principle)
### Q49: What bean scopes does Spring support? Explain them.
> Topic: **Spring**<br/>Difficulty: ⭐⭐⭐⭐

The Spring Framework supports following five scopes, three of which are available only if you use a web-aware ApplicationContext.

*   **singleton** − This scopes the bean definition to a single instance per Spring IoC container.
*   **prototype** − This scopes a single bean definition to have any number of object instances.
*   **request** − This scopes a bean definition to an HTTP request. Only valid in the context of a web-aware Spring ApplicationContext.
*   **session** − This scopes a bean definition to an HTTP session. Only valid in the context of a web-aware Spring ApplicationContext.
*   **global-session** − This scopes a bean definition to a global HTTP session. Only valid in the context of a web-aware Spring ApplicationContext.

🔗 **Source:** [tutorialspoint.com](https://www.tutorialspoint.com/spring/spring_interview_questions.htm)
### Q50: What is Weaving?
> Topic: **Spring**<br/>Difficulty: ⭐⭐⭐⭐

Weaving is the process of linking _aspects_ with other application types or objects to create an advised object.

🔗 **Source:** [tutorialspoint.com](https://www.tutorialspoint.com/spring/spring_interview_questions.htm)
### Q51: What is the difference between concern and cross-cutting concern in Spring AOP?
> Topic: **Spring**<br/>Difficulty: ⭐⭐⭐⭐

* **Concern** − Concern is behavior which we want to have in a module of an application. Concern may be defined as a functionality we want to implement. Issues in which we are interested define our concerns.
* **Cross-cutting concern** − It's a concern which is applicable throughout the application and it affects the entire application. e.g. logging , security and data transfer are the concerns which are needed in almost every module of an application, hence are cross-cutting concerns.

🔗 **Source:** [tutorialspoint.com](https://www.tutorialspoint.com/spring/spring_interview_questions.htm)
### Q52: What are some benefits of using Spring Transactions?
> Topic: **Spring**<br/>Difficulty: ⭐⭐⭐⭐

*   Provide a consistent programming model across different transaction APIs such as JTA, JDBC, Hibernate, JPA, and JDO
*   Support declarative transaction management
*   Provide a simpler API for programmatic transaction management than some complex transaction APIs such as JTA
*   Integrate very well with Spring’s various data access abstractions

🔗 **Source:** [baeldung.com](https://www.baeldung.com/spring-interview-questions)
### Q53: What is Aspect-Oriented Programming?
> Topic: **Spring**<br/>Difficulty: ⭐⭐⭐⭐

_Aspects_ enable the modularization of cross-cutting concerns such as transaction management that span multiple types and objects by adding extra behavior to already existing code without modifying affected classes.

🔗 **Source:** [baeldung.com](https://www.baeldung.com/spring-interview-questions)
### Q54: What is Spring WebFlux?
> Topic: **Spring**<br/>Difficulty: ⭐⭐⭐⭐

Spring WebFlux is Spring’s reactive-stack web framework, and it’s an alternative to Spring MVC. In order to achieve this reactive model and be highly scalable, the entire stack is non-blocking.

🔗 **Source:** [baeldung.com](https://www.baeldung.com/spring-interview-questions)
### Q55: Compare @Component (v2.5) versus @Bean (v 3.0)
> Topic: **Spring**<br/>Difficulty: ⭐⭐⭐⭐

Would it have been possible to re-use the @Component annotation instead of introducing @Bean annotation? 

---
`@Component` and `@Bean` do two quite different things, and shouldn't be confused.

* `@Component` (and `@Service` and `@Repository`) are used to auto-detect and auto-configure beans using classpath scanning. There's an implicit one-to-one mapping between the annotated class and the bean (i.e. one bean per class). Control of wiring is quite limited with this approach, since it's purely declarative.

* `@Bean` is used to *explicitly* declare a single bean, rather than letting Spring do it

_To answer your question_:
Sure, probably; but they chose not to, since the two are quite different. Spring's already confusing enough without muddying the waters further.

🔗 **Source:** [stackoverflow.com](https://stackoverflow.com/questions/17193365/what-in-the-world-are-spring-beans)
### Q56: What's the difference between the Dependency Injection and Service Locator patterns?
> Topic: **Design Patterns**<br/>Difficulty: ⭐⭐⭐⭐⭐

* With the **ServiceLocator**, the class is still responsible for creating its dependencies. It just uses the service locator to do it. 
* **Service locators** hide dependencies - you can't tell by looking at an object whether it hits a database or not (for example) when it obtains connections from a locator. 
* With **DI**, the class is given it's dependencies. It neither knows, nor cares where they come from. 

One important result of this is that the DI example is much easier to unit test -- because you can pass it mock implementations of its dependent objects. You could combine the two -- and inject the service locator (or a factory), if you wanted.

🔗 **Source:** [stackoverflow.com](https://stackoverflow.com/questions/1557781/whats-the-difference-between-the-dependency-injection-and-service-locator-patte)
### Q57: What are the layers of RMI Architecture?
> Topic: **Java**<br/>Difficulty: ⭐⭐⭐⭐⭐

The RMI architecture consists of the following layers:

* Stub and Skeleton layer: This layer lies just beneath the view of the developer. This layer is responsible for intercepting method calls made by the client to the interface and redirect these calls to a remote RMI Service.
* Remote Reference Layer: The second layer of the RMI architecture deals with the interpretation of references made from the client to the server’s remote objects. This layer interprets and manages references made from clients to the remote service objects. The connection is a one-to-one (unicast) link.
* Transport layer: This layer is responsible for connecting the two JVM participating in the service. This layer is based on TCP/IP connections between machines in a network. It provides basic connectivity, as well as some firewall penetration strategies.

🔗 **Source:** [github.com/snowdream](https://github.com/snowdream/115-Java-Interview-Questions-and-Answers)
### Q58: What is the difference between association, aggregation and composition?
> Topic: **OOP**<br/>Difficulty: ⭐⭐⭐⭐⭐

* **Association** is a relationship where all objects have their own lifecycle and there is no owner.

 Let's take an example of Teacher and Student. Multiple students can associate with single teacher and single student can associate with multiple teachers, but there is no ownership between the objects and both have their own lifecycle. Both can be created and deleted independently.
 
* **Aggregation** is a specialised form of Association where all objects have their own lifecycle, but there is ownership and child objects can not belong to another parent object.

 Let's take an example of Department and teacher. A single teacher can not belong to multiple departments, but if we delete the department, the teacher object will *not* be destroyed. We can think about it as a “has-a” relationship.
 
* **Composition** is again specialised form of Aggregation and we can call this as a “death” relationship. It is a strong type of Aggregation. Child object does not have its lifecycle and if parent object is deleted, all child objects will also be deleted.

 Let's take again an example of relationship between House and Rooms. House can contain multiple rooms - there is no independent life of room and any room can not belong to two different houses. If we delete the house - room will automatically be deleted.

 Let's take another example relationship between Questions and Options. Single questions can have multiple options and option can not belong to multiple questions. If we delete the questions, options will automatically be deleted.

🔗 **Source:** [stackoverflow.com](https://stackoverflow.com/questions/885937/what-is-the-difference-between-association-aggregation-and-composition)
### Q59: What are some of the best practices for Spring Framework?
> Topic: **Spring**<br/>Difficulty: ⭐⭐⭐⭐⭐

1.  Avoid version numbers in schema reference, to make sure we have the latest configs.
2.  Divide spring bean configurations based on their concerns such as spring-jdbc.xml, spring-security.xml.
3.  For spring beans that are used in multiple contexts in Spring MVC, create them in the root context and initialize with listener.
4.  Configure bean dependencies as much as possible, try to avoid autowiring as much as possible.
5.  For application-level properties, the best approach is to create a property file and read it in the spring bean configuration file.
6.  For smaller applications, annotations are useful but for larger applications, annotations can become a pain. If we have all the configuration in XML files, maintaining it will be easier.
7.  Use correct annotations for components for understanding the purpose easily. For services use @Service and for DAO beans use @Repository.
8.  Spring framework has a lot of modules, use what you need. Remove all the extra dependencies that get usually added when you create projects through Spring Tool Suite templates.
9.  If you are using Aspects, make sure to keep the join pint as narrow as possible to avoid advice on unwanted methods. Consider custom annotations that are easier to use and avoid any issues.
10.  Use dependency injection when there is an actual benefit, just for the sake of loose-coupling don’t use it because it’s harder to maintain.

🔗 **Source:** [journaldev.com](https://www.journaldev.com/2696/spring-interview-questions-and-answers#spring-best-practices)
### Q60: How does autowiring work in Spring?
> Topic: **Spring**<br/>Difficulty: ⭐⭐⭐⭐⭐

First, and most important - all Spring beans are managed - they "live" inside a container, called "application context".

Second, each application has an entry point to that context. Web applications have a Servlet, JSF uses a el-resolver, etc. Also, there is a place where the application context is bootstrapped and all beans - autowired. In web applications this can be a startup listener.

Autowiring happens by placing an instance of one bean into the desired field in an instance of another bean. Both classes should be beans, i.e. they should be defined to live in the application context.

What is "living" in the application context? This means that the _context_ instantiates the objects, not you. I.e. - you never make `new UserServiceImpl()` - the container finds each injection point and sets an instance there.

🔗 **Source:** [stackoverflow.com](https://stackoverflow.com/questions/1079114/where-does-the-transactional-annotation-belong)

> *Thanks 🙌 for reading and good luck on your interview!* <br/>*Please share this article with your fellow devs if you like it!* <br/>*Check more FullStack Interview Questions & Answers on 👉 [www.fullstack.cafe](https://www.fullstack.cafe)*