0% found this document useful (0 votes)
22 views26 pages

Interview Questions

Uploaded by

Ashish Sharma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views26 pages

Interview Questions

Uploaded by

Ashish Sharma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

List of Interview Questions

S.No Topic
1 CoreJava
2. JDBC
3. Hibernate
4. Spring
5. Spring Boot interview
Core Java Interview Questions
1. Which is superclass of all your java object
Ans: object class

2. Diff Between method and constructor


Ans:
Constructor is used to initialize the value to object but method is used to
expose the object value

Constructor does not have return type but method must have return type

Constructor name should be the same name as class name but method may or
maynot

3. What is the use of static block in java


Ans: static block is used to declare inside the class for initialize the static
variables
static block will execute some statement in class level before execute main
method

4. Diff between abstract class and interface


Ans: abstract class we declare to achieve the partially abstraction but interface
we achieve fully abstraction
We cannot achieve multiple inheritance in abstract class but we can using
interface
More than one abstract class we cannot extend by sub class but more than
one interface we can implement
5. Diff between method overloading and method overriding
Ans: We have same method multiple times with diff parameter inside the
class we called as method overloading
If we have same method with same parameter but different class we called as
method overriding
By using method overloading we perform same task more than one time by
single object
By using method overriding we perform same task by diff object in diff way.

6. Diff Between checked and unchecked exception


Ans: checked exception raised during the compilation of code which can handle
by developer.
Checked exceptions are raised whenever trying to access any resource
Outside JVM
Unchecked exception raised during the runtime and it raised an exception
based on scenario.

7. Why Java Does not support multiple inheritance


Ans: If we have same method in my 2 super class and sub class trying to call
this method then it does not know which super class method should
execute so JVM throws a compilation error
Thats why java does not support multiple inheritance through class level but
the same we can achieve through interface

8. What is a functional interface


Ans: A functional interface is a special interface added in java 8 version
Where we can declare only one abstract method and other could be static
or default methods
It has restriction to define more than one abstract methods
9. Which class is super class of all your Exception class
Ans: Throwable class

10. Which class is superclass of all your RuntimeException class


Ans: Exception

11. Difference between throw and throws keyword in java


Ans: throw keyword is used to throw an exception by creating an instance of
class and it should declare inside your method.
throws keyword is used to declare an exception for method signature to
throw a particular exception while you call it.

12. Difference between Array and ArrayList


Ans: Array is used for declaring a static array but ArrayList is used for Dynamic
Array.
Array maintained with fixed array size but ArrayList maintained dynamic
Array (Growable Array object)
We have to write the method implementation to achieve data manipulation
in array but All the method already implemented in ArrayList so we can use
it directly as per need
ArrayList is better option for developer as its part collection framework and
have better use.

13. Diff Between Comparable and Comparator inteface


Ans: Comparable interface is used to do single sorting of object elements. we
do the override compareTo()
Comparator interface is used for multiple sorting of object elements. we do
the override compare()
14. What is a Marker interface
Ans: Marker interface is an empty interface which does not have any methods.

15. Tell me some marker interface in java


Ans: Serializable, Cloneable etc...

16. Diff between List and Set interface


Ans: List can allow to store duplicate elements where as set can contain unique
elements.

17. What is generics in collection


Ans: Generics is used basically in collection framework to create a type safe
objects
We no need to do type casting..and we can declare a specific object type in
collection

18. diff between final, finally and finalize in java


Ans: final keyword is used to declare final variables, methods and class
finally keyword is used to make a finally block which we want execute always
end of the program (No matter whether exception is there or not)
finalize() is a method which invoke if any java object is called by jvm for
garbage collection

19. How Map interface is diff from collection


Ans: Map has introduced in java basically to maintain both key-value pairs
designing as data structure form
But Collection does can allow to store only values in form of List, Set and
Queue interface

20. What are the New Features Added in Java 8 version


Ans: Lambda expression
Stream API
default and static method allowed in interface
Functional interface
21. What is use of synchronized method
Ans: Synchronized is used to declare a method or block and it will allow only
one thread to complete its task
and other thread will be in lock until the current thread has not exit.

22. How to create immutable object in java


Ans: Step-1 Create a class as final
Step-2 Declare all the properties as private
Step-3 Dont write setter() method only write getter()

23. Explain Thread LifeCycle


Ans: Step-1 New Thread
Step-2 Runnable
Step-3 Running
Step-4 Non-Runnable
Step-5 Dead

24. What is a serialization


Ans: serialization is a process to write the object data in binary stream
25. What is Atomic variables in java
Ans: Atomic variables is used in multi threading if more than one threads wants
to update their status.

26. What is use of transient keyword in java


Ans: transient keyword is used to declare variables which i dont want to make
serialize

27. diff between Hashtable and HashMap


Ans: https://www.geeksforgeeks.org/differences-between-hashmap-and-
hashtable-in-java/

28. Diff Between execute() and executeUpdate()


Ans: execute and executeUpdate() both is used to execute sql queries
but execute() return boolean and excuteUpdate() returns int i.e how many
records reflected after query execution

29. How to create custom exception in java


Ans: Step-1 Create class which need to extends Exception class
Step-2 Introduce a constructor of class which can invoke to exception object
to throws an exception

30. How Stream API is important for java app.


Ans: Stream API is basically used for filter the data from collection
So it is a better option to choose because it has some inbuilt methods to
filter data from List,Set and Map
31. What is a Lambda Expression
Ans: It a new features added in java 8 version to implement abstract method
direct by interface instead of implemented by any class.

32. How many ways we can print exception message in java program..?
Ans: We can print the exception message in different ways
1. by using printstackTrace()----->Trace the exception line of code
2. getMessage()
3. toString()
4. print the exception class ref
33)What all are different concepts of OOPS(Object Oriented Programming
System)
Encapsulation
Abstraction
Polymorphism
Inheritance
34)What is the difference between abstract classes and interfaces?

Abstract class Interface

1) Abstract class can have abstract and non- Interface can have only abstract methods. Since
abstract methods. Java 8, it can have default and static
methods also.

2) Abstract class doesn't support multiple Interface supports multiple inheritance.


inheritance.

3) Abstract class can have final, non-final, Interface has only static and final variables.
static and non-static variables.

4) Abstract class can provide the Interface can't provide the implementation of
implementation of interface. abstract class.
5) The abstract keyword is used to declare The interface keyword is used to declare
abstract class. interface.

6) An abstract class can extend another Java An interface can extend another Java interface
class and implement multiple Java interfaces. only.

7) An abstract class can be extended using An interface can be implemented using keyword
keyword "extends". "implements".

8) A Java abstract class can have class Members of a Java interface are public by default.
members like private, protected, etc.

35)What is the difference between JVM,JDK and JRE


https://www.geeksforgeeks.org/differences-jdk-jre-jvm/
35)What would happen if you don’t write main method.
The program will compile but not execute.
36)What are JDBC statements?

In JDBC, Statements are used to send SQL commands to the database and receive data
from the database. There are various methods provided by JDBC statements such as
execute(), executeUpdate(), executeQuery, etc. which helps you to interact with the
database.

There is three type of JDBC statements given in the following table.

Statements Explanation

Statement Statement is the factory for resultset. It is used for general purpose access
to the database. It executes a static SQL query at runtime.

PreparedStatement The PreparedStatement is used when we need to provide input parameters


to the query at runtime.

CallableStatement CallableStatement is used when we need to access the database stored


procedures. It can also accept runtime parameters.

37) What are the differences between execute, executeQuery,


and executeUpdate?
execute executeQuery executeUpdate

The execute method can be used The executeQuery The executeUpdate method can
for any SQL statements(Select and method can be used only be used to update/delete/insert
Update both). with the select operations in the database.
statement.

The execute method returns a The executeQuery() The executeUpdate() method


boolean type value where true method returns a returns an integer value
indicates that the ResultSet s ResultSet object which representing the number of
returned which can later be contains the data records affected where 0
extracted and false indicates that retrieved by the select indicates that query returns
the integer or void value is statement. nothing.
returned.
38)What is ResultSet

A ResultSet object maintains a cursor pointing to its current row of data. Initially the cursor is positioned
before the first row. The next method moves the cursor to the next row, and because it returns false when
there are no more rows in the ResultSet object, it can be used in a while loop to iterate through the result
set.

39)
Hibernate Interview Questions

1) What are the major advantages of Hibernate Framework?

a. It is open-sourced and lightweight.


b. Performance of Hibernate is very fast.
c. Helps in generating database independant queries.
d. Provides facilities to automatically create a table.
e. It provides query statistics and database status.
2. What is Many-to-Many association in Hibernate?
a. Many-to-Many mapping requires an entity attribute and a @ManyToMany
annotation. It can either be unidirectional and bidirectional. In Unidirectional, the
attributes model the association and you can use it to navigate it in your domain
model or JPQL queries. The annotation tells Hibernate to map a Many-to-Many
association. The bidirectional relationship, mapping allows you to navigate the
association in both directions.

3. What is Session in Hibernate and how to get it?


a. Hibernate Session is the interface between Java application layer and Hibernate. It is
used to get a physical connection with the database. The Session object created is
lightweight and designed to be instantiated each time an interaction is needed with
the database. This Session provides methods to create, read, update and delete
operations for a constant object. To get the Session, you can execute HQL queries,
SQL native queries using the Session object
4. What are the collection types in Hibernate?
a. There are five collection types in hibernate used for one-to-many relationship
mappings.
b. Bag
c. Set
d. List
e. Array
f. Map
5. What is one-to-one association?
a. A one-to-one association is similar to many-to-one association with a difference that
the column will be set as unique. For example an address object can be associated
with a single employee object.
b. <many-to-one> element is used to define one-to-one association. The name
attribute is set to the defined variable in the parent class. The column attribute is
used to set the column name in the parent table which is set to unique so that only
one object can be associated with an other object.
6. What is one-to-many association?
a. In One-to-Many mapping association, an object can be can be associated with
multiple objects. For example Employee object relates to many Certificate objects.
b. A One-to-Many mapping can be implemented using a Set java collection that does
not contain any duplicate element.
c. <one-to-many> element of set element indicates that one object relates to many
other objects.
7. What is HQL?
a. HQL stands for Hibernate Query Language. It takes java objects in the same way as
SQL takes tables. HQL is a Object Oriented Query language and is database
independent.
8. When do you use merge() and update() in Hibernate?
a. update(): If you are sure that the Hibernate Session does not contain an already
persistent instance with the same id .
b. merge(): Helps in merging your modifications at any time without considering the
state of the Session.
9. Difference between the first and second level cache in Hibernate?
a. The first-level cache is maintained at Session level while the second level cache is
maintained at a SessionFactory level and is shared by all sessions.
10. Difference between sorted and ordered collection in Hibernate?
a. sorted collection sort the data in JVM’s heap memory using Java’s collection
framework sorting methods. The ordered collection is sorted using order by clause
in the database itself.
b. Note: A sorted collection is more suited for small dataset but for a large dataset, it’s
better to use ordered collection to avoid
11. Difference between the transient, persistent and detached state in Hibernate?
a. Transient state: New objects are created in the Java program but are not associated
with any Hibernate Session.
b. Persistent state: An object which is associated with a Hibernate session is called
Persistent object. While an object which was earlier associated with Hibernate
session but currently it’s not associate is known as a detached object. You can call
save() or persist() method to store those object into the database and bring them
into the Persistent state.
c. Detached state: You can re-attach a detached object to Hibernate sessions by calling
either update() or saveOrUpdate() method.
12. Difference between managed associations and Hibernate associations?
a. Managed associations: Relate to container management persistence and are bi-
directional.
b. Hibernate Associations: These associations are unidirectional.

13) Difference between ORM and JDBC


Why do you need to choose Hibernate? Hibernate has all main benefits such as portability,
productivity, maintainability, and also it’s a free and open source framework.

Hibernate advantages in details:

1. It removes a lot of repetitive code from the JDBC API, and therefore, the
code is easier to read, write, and support.
2. Hibernate Query Language (HQL) is fully object-oriented and more close to
the Java programming language comparing to SQL in JDBC. Also, HQL is
a Database-independent query that allows you to switch between different
databases easily.
3. Hibernate supports caching, which improves performance.
- First-level is a mandatory Session cache.
- Second-level is an optional cache. Hibernate has a lot of cache providers
for this level, the most popular are: EHCache, OSCache, warmCache, JBoss
Cache, etc.
- Query-level is an optional cache for query result sets.
4. Lazy load that also improves performance.
5. Hibernate supports JPA annotations, which means the code is portable to
other ORM frameworks.
6. Hibernate has a connection pool.
7. You do not need to handle exceptions.Hibernate allows database
management (for example creating tables), JDBC can only work with
existing DB tables.
8. Hibernate supports inheritance, associations, and collections that are not
available in the JDBC API.
Spring Interview Questions
List the advantages of Spring Framework.

• Because of Spring Frameworks layered architecture, you can use what you
need and leave which you don’t.
• Spring Framework enables POJO (Plain Old Java Object) Programming which
in turn enables continuous integration and testability.
• JDBC is simplified due to Dependency Injection and Inversion of Control.
• It is open-source and has no vendor lock-in.

4. What are the different features of Spring Framework?

Following are some of the major features of Spring Framework :

• Lightweight: Spring is lightweight when it comes to size and transparency.


• Inversion of control (IOC): The objects give their dependencies instead of
creating or looking for dependent objects. This is called Inversion Of Control.
• Aspect oriented Programming (AOP): Aspect oriented programming in
Spring supports cohesive development by separating application business
logic from system services.
• Container: Spring Framework creates and manages the life cycle and
configuration of the application objects.
• MVC Framework: Spring Framework’s MVC web application framework is
highly configurable. Other frameworks can also be used easily instead of Spring
MVC Framework.
• Transaction Management: Generic abstraction layer for transaction
management is provided by the Spring Framework. Spring’s transaction
support can be also used in container less environments.
• JDBC Exception Handling: The JDBC abstraction layer of the Spring offers
an exception hierarchy, which simplifies the error handling strategy.

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

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

• Spring Core Container – This layer is basically the core of Spring


Framework. It contains the following modules :

a. Spring Core
b. Spring Bean
c. SpEL (Spring Expression Language)
d. Spring Context

• Data Access/Integration – This layer provides support to interact with the


database. It contains the following modules :

a. JDBC (Java DataBase Connectivity)


b. ORM (Object Relational Mapping)
c. OXM (Object XML Mappers)
d. JMS (Java Messaging Service)
e. Transaction

• Web – This layer provides support to create web application. It contains the
following modules :

a. Web
b. Web – MVC
c. Web – Socket
d. Web – Portlet

• Aspect Oriented Programming (AOP) – In this layer you can use


Advices, Pointcuts etc., to decouple the code.
• Instrumentation – This layer provides support to class instrumentation and
classloader implementations.
• Test – This layer provides support to testing with JUnit and TestNG.
Few Miscellaneous modules are given below:

• Messaging – This module provides support for STOMP. It also supports an


annotation programming model that is used for routing and processing STOMP
messages from WebSocket clients.
• Aspects – This module provides support to integration with AspectJ.

6. What is a Spring configuration file?

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

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

A Spring application, generally consists of following components:

• Interface: It defines the functions.


• Bean class: It contains properties, its setter and getter methods, functions etc.
• Spring Aspect Oriented Programming (AOP): Provides the functionality of
cross-cutting concerns.
• Bean Configuration File: Contains the information of classes and how to
configure them.
• User program: It uses the function.

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

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

1. As a Full-fledged Spring web application.


2. As a third-party web framework, using Spring Frameworks middle-tier.
3. For remote usage.
4. As Enterprise Java Bean which can wrap existing POJOs (Plain Old Java
Objects).
Dependency Injection/ IoC Container – Spring Interview Questions
9. What is Spring IOC Container?

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

10. What do you mean by Dependency Injection?

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

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

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

• Constructor Injection
• Setter Injection
• Interface Injection

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

12. Differentiate between constructor injection and setter injection.

Constructor Injection vs Setter Injection


Constructor Injection Setter Injection

There is no partial injection. There can be partial injection.

It doesn’t override the setter property. It overrides the constructor property.


It will create a new instance if any modification is It will not create new instance if any
done. modification is done.

It works better for many properties. It works better for few properties.

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

a. BeanFactory: BeanFactory is like a factory class that contains a collection of beans.


It instantiates the bean whenever asked for by clients.
b. ApplicationContext: The ApplicationContext interface is built on top of the
BeanFactory interface. It provides some extra functionality on top BeanFactory.

14. Differentiate between BeanFactory and ApplicationContext.

BeanFactory vs ApplicationContext
BeanFactory ApplicationContext

It is an interface defined in It is an interface defined in


org.springframework.beans.factory.BeanFactory org.springframework.context.ApplicationContext

It uses Lazy initialization It uses Eager/ Aggressive initialization

It explicitly provides a resource object using the syntax It creates and manages resource objects on its own

It doesn’t supports internationalization It supports internationalization

It doesn’t supports annotation based dependency It supports annotation based dependency

15. List some of the benefits of IoC.

Some of the benefits of IoC are:

• It will minimize the amount of code in your application.


• It will make your application easy to test because it doesn’t require any singletons or
JNDI lookup mechanisms in your unit test cases.
• It promotes loose coupling with minimal effort and least intrusive mechanism.
• It supports eager instantiation and lazy loading of the services.

Let’s move on to the next section of Spring Interview Questions, that is Spring Beans
Interview Questions.

Spring Beans – Spring Interview Questions


16. Explain Spring Beans?

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

container.

17. How configuration metadata is provided to the Spring container?

Configuration metadata can be provided to Spring container in following ways:

• XML-Based configuration: In Spring Framework, the dependencies and the services


needed by beans are specified in configuration files which are in XML format. These
configuration files usually contain a lot of bean definitions and application specific
configuration options. They generally start with a bean tag. For example:

1 <bean id="studentbean" class="org.edureka.firstSpring.StudentBean">

2 <property name="name" value="Edureka"></property>

3 </bean>

• Annotation-Based configuration: Instead of using XML to describe a bean wiring,


you can configure the bean into the component class itself by using annotations on the
relevant class, method, or field declaration. By default, annotation wiring is not turned
on in the Spring container. So, you need to enable it in your Spring configuration file
before using it. For example:

1 <beans>

2 <context:annotation-config/>

3 <!-- bean definitions go here -->

4 </beans>

• Java-based configuration: The key features in Spring Framework’s new Java-


configuration support are @Configuration annotated classes and @Bean annotated
methods.

18. How many bean scopes are supported by Spring?

The Spring Framework supports five scopes. They are:

• Singleton: This provides scope for the bean definition to single instance per
Spring IoC container.
• Prototype: This provides scope for a single bean definition to have any number
of object instances.
• Request: This provides scope for a bean definition to an HTTP-request.
• Session: This provides scope for a bean definition to an HTTP-session.
• Global-session: This provides scope for a bean definition to an Global HTTP-
session.
19. What is the Bean life cycle in Spring Bean Factory Container?

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

1. The Spring container instantiates the bean from the bean’s definition in the XML
file.
2. Spring populates all of the properties using the dependency injection, as
specified in the bean definition.
3. The factory calls setBeanName() by passing the bean’s ID, if the bean
implements the BeanNameAware interface.
4. The factory calls setBeanFactory() by passing an instance of itself, if the bean
implements the BeanFactoryAware interface.
5. preProcessBeforeInitialization() methods are called if there are any
BeanPostProcessors associated with the bean.
6. If an init-method is specified for the bean, then it will be called.
7. Finally, postProcessAfterInitialization() methods will be called if there are any
BeanPostProcessors associated with the bean.

20.What do you understand by auto wiring and name the different


modes of it?

The Spring container is able to autowire relationships between the collaborating


beans. That is, it is possible to let Spring resolve collaborators for your bean
automatically by inspecting the contents of the BeanFactory.
Different modes of bean auto-wiring are:

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

21. What are the limitations with auto wiring?

Following are some of the limitations you might face with auto wiring:

• Overriding possibility: You can always specify dependencies using


<constructor-arg> and <property> settings which will override autowiring.
• Primitive data type: Simple properties such as primitives, Strings and
Classes can’t be autowired.
• Confusing nature: Always prefer using explicit wiring because autowiring is
less precise.
22. What do you mean by Annotation-based container configuration?

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

1 @Configuration
2 public class AnnotationConfig
3 {
4 @Bean
5 public MyDemo myDemo()
{ return new MyDemoImpll(); }
6 }
7
25. How annotation wiring can be turned on in Spring?

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

<beans xmlns="<a href="http://www.springframework.org/schema/beans">http://ww


1 href="http://www.w3.org/2001/XMLSchema-instance">http://www.w3.org/2
2 href="http://www.springframework.org/schema/context">http://www.
3 <context:annotation-config
<beans ………… />
4 </beans>
26. What’s the difference between @Component, @Controller,
@Repository & @Service annotations in Spring?

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

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

@Service: This annotation is a specialization of the component annotation. It doesn’t


provide any additional behavior over the @Component annotation. You can use
@Service over @Component in service-layer classes as it specifies intent in a better
way.

@Repository: This annotation is a specialization of the @Component annotation with


similar use and functionality. It provides additional benefits specifically for DAOs. It
imports the DAOs into the DI container and makes the unchecked exceptions eligible
for translation into Spring DataAccessException.

27. What do you understand by @Required annotation?

@Required is applied to bean property setter methods. This annotation simply


indicates that the affected bean property must be populated at the configuration
time with the help of an explicit property value in a bean definition or with autowiring.
If the affected bean property has not been populated, the container will throw
BeanInitializationException.

For example:

1
public class Employee
2 {
3 private String name;
4 @Required
5 public void setName(String name)
6 {this.name=name; }
public string getName()
7 { return name; }
8 }
9
28. What do you understand by @Autowired annotation?

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

For Example:

1
public class Employee
2 {
3 private String name;
4 @Autowired
5 public void setName(String name)
6 {this.name=name; }
public string getName()
7 { return name; }
8 }
9
29. What do you understand by @Qualifier annotation?

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

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

Employee.java

1 public class Employee


2 {
private String name;
3 @Autowired
4 public void setName(String name)
5 { this.name=name; }
6 public string getName()
7 { return name; }
}
8
9
EmpAccount.java

1
2 public class EmpAccount
{
3 private Employee emp;
4 @Autowired
5 @Qualifier(emp1)
6 public void showName()
{
7 System.out.println(“Employee name : ”+emp.getName);
8 }
9 }
10
30. What do you understand by @RequestMapping annotation?

@RequestMapping annotation is used for mapping a particular HTTP request method


to a specific class/ method in controller that will be handling the respective
request. This annotation can be applied at both levels:

• Class level : Maps the URL of the request


• Method level: Maps the URL as well as HTTP request method
Spring Boot interview Questions
1)Spring vs. Spring Boot.
A web application framework based on
A module of Spring
Java
Provides tools and libraries to create Used to create a Spring application
customized web applications project which can just run/ execute
Spring is more complex than Spring Spring Boot is less complex than the
Boot Spring framework
Takes an opinionated view of a
Takes an unopinionated view
platform

2)Mention the advantages of SpringBoot


• Provides auto-configuration to load a set of default configuration for a quick start
of the application
• Creates stand-alone applications with a range of non-functional features that are
common to large classes of projects
• It comes with embedded tomcat, servlet containers jetty to avoid the usage of WAR
files
• Spring Boot provides an opinionated view to reduce the developer effort and
simplify maven configurations
• Provides CLI tool to develop and test applications
• Comes with Spring Boot starters to ensure dependency management and also
provides various security metrics
• Consists of a wide range of APIs for monitoring and managing applications in dev
and prod.
• Integrates with Spring Ecosystem like Spring JDBC, Spring ORM, Spring Data,
Spring Security easily by avoiding boilerplate code.

Q3. Can we change the port of the embedded Tomcat server in


Spring boot?

Yes, we can change the port of the embedded tomcat server by using the
application properties file. In this file, you have to add a property of “server.port”
and assign it to any port you wish to. For example, if you want to assign it to 8081,
then you have to mention server.port=8081.
Q4. What are the @RequestMapping and @RestController
annotation in Spring Boot used for?

@RequestMapping @RestController
This annotation is used to provide the
This annotation is used to add the
routing information and tells to Spring
@ResponseBody and @Controller
that any HTTP request must be mapped
annotation to the class
to the respective method.
To use this annotation, you have to To use this annotation, you have to
import org.springframework.web. import org.springframework.web.
bind.annotation.RequestMapping; bind.annotation.RestController;

Q5. What is the difference between RequestMapping and


GetMapping?

The @GetMapping is a composed annotation that acts as a shortcut


for @RequestMapping(method = RequestMethod.GET). Both these methods
support the consumes. The consume options are :

consumes = “text/plain”
consumes = {“text/plain”, “application/*”}

Q6. What all annotations are part of SpringBootApplication annotation

Spring Boot @SpringBootApplication annotation is used to mark a configuration


class that declares one or more @Bean methods and also triggers auto-
configuration and component scanning. It's same as declaring a class with
@Configuration, @EnableAutoConfiguration and @ComponentScan annotations. 03-
Aug-2022

You might also like