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

Full Stack Java Ques

The document provides a comprehensive overview of Java-related concepts, frameworks, and technologies, including JDK, JRE, Spring Framework, Hibernate, and RESTful services. It covers key differences between various data structures and annotations in Spring, as well as the advantages of using Spring Boot and Hibernate. Additionally, it explains core programming concepts such as dependency injection, MVC architecture, and transaction management.

Uploaded by

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

Full Stack Java Ques

The document provides a comprehensive overview of Java-related concepts, frameworks, and technologies, including JDK, JRE, Spring Framework, Hibernate, and RESTful services. It covers key differences between various data structures and annotations in Spring, as well as the advantages of using Spring Boot and Hibernate. Additionally, it explains core programming concepts such as dependency injection, MVC architecture, and transaction management.

Uploaded by

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

1. What is the difference between JDK and JRE?

 Answer:
o JDK (Java Development Kit): It includes JRE and tools required to develop
Java applications, such as a compiler (javac), debugger, etc.
o JRE (Java Runtime Environment): It provides libraries and other
components to run Java programs. It includes JVM but does not have
development tools.

2. What is Spring Framework?

 Answer: Spring is an open-source framework for building Java-based enterprise


applications. It simplifies development by providing comprehensive infrastructure
support like dependency injection, aspect-oriented programming (AOP), transaction
management, etc.

3. Explain the concept of Dependency Injection (DI) in Spring.

 Answer: Dependency Injection (DI) is a design pattern in which an object's


dependencies are injected at runtime, rather than the object creating them. It improves
code modularity and testability.

4. What is the difference between an ArrayList and a LinkedList in Java?

 Answer:
o ArrayList: Implements the List interface and stores elements in a dynamic
array. It provides fast random access but slower insertions and deletions in the
middle of the list.
o LinkedList: Implements the List interface using a doubly linked list. It is
faster for inserting and deleting elements but slower for random access.

5. What is Hibernate and how is it different from JDBC?

 Answer: Hibernate is an ORM (Object Relational Mapping) framework that


simplifies database interactions by mapping Java objects to database tables. Unlike
JDBC, which requires developers to manually write SQL queries, Hibernate
automatically generates SQL queries and handles database operations.

6. What is the role of @Entity in Hibernate?

 Answer: @Entity is used to annotate a class as an entity in Hibernate, which means it


is a persistent object. The class will be mapped to a table in the database.

7. What is the difference between GET and POST methods in HTTP?

 Answer:
o GET: Retrieves data from the server. It appends data to the URL and is visible
to the user.
o POST: Sends data to the server. Data is sent in the body of the request and is
not visible in the URL.

8. What is RESTful Web Service?

 Answer: REST (Representational State Transfer) is an architectural style for


designing networked applications. It uses HTTP methods like GET, POST, PUT,
DELETE for communication. RESTful web services are stateless, scalable, and can
be consumed by various clients.

9. Explain MVC architecture.

 Answer: MVC (Model-View-Controller) is a design pattern that separates the


application into three components:
o Model: Represents the data and business logic.
o View: Displays the data to the user.
o Controller: Handles user input and updates the model and view accordingly.

10. What is a Session in Java and how is it different from Cookies?

 Answer:
o Session: A server-side storage of user data, used to store user-specific
information across multiple pages during a single visit.
o Cookies: A client-side storage mechanism to store small amounts of data in
the user's browser for session management.

11. What is the difference between HashMap and TreeMap in Java?

 Answer:
o HashMap: Implements the Map interface, stores key-value pairs in a hash
table, and does not guarantee any order of elements. It allows null values and
keys.
o TreeMap: Implements the SortedMap interface, stores key-value pairs in a
red-black tree, and maintains the order of elements according to the natural
ordering of the keys or a custom comparator.

12. Explain the difference between final, finally, and finalize in Java.

 Answer:
o final: Used to define constants, prevent method overriding, and prevent
inheritance.
o finally: A block that follows try-catch, used for code that must execute
regardless of whether an exception was thrown or not (e.g., closing resources).
o finalize: A method in Object class, used by the garbage collector before an
object is destroyed.

13. What is the purpose of the @Autowired annotation in Spring?


 Answer: The @Autowired annotation is used in Spring for automatic dependency
injection. It allows Spring to resolve and inject collaborating beans into a class.

14. Explain the concept of Java Streams.

 Answer: Java Streams is an API introduced in Java 8 for processing sequences of


elements (like collections) in a functional style. It allows operations like filtering,
mapping, and reducing to be performed efficiently on data.

15. What is the difference between throw and throws in Java?

 Answer:
o throw: Used to explicitly throw an exception from a method or block of code.
o throws: Used in method signatures to declare that a method may throw one or
more exceptions.

16. What is the @Component annotation in Spring?

 Answer: The @Component annotation is used in Spring to declare a class as a Spring-


managed bean. The class is automatically registered as a bean in the application
context, making it available for dependency injection.

17. What is Spring Boot and how is it different from the traditional Spring
framework?

 Answer: Spring Boot is a simplified, convention-over-configuration framework built


on top of Spring. It eliminates the need for XML configuration, provides embedded
servers like Tomcat, and offers auto-configuration to quickly set up and run Spring
applications.

18. What are the different types of Spring Boot starters?

 Answer: Spring Boot starters are pre-configured sets of dependencies that simplify
development. Common types include:
o spring-boot-starter-web: For building web applications.
o spring-boot-starter-data-jpa: For working with databases using JPA.
o spring-boot-starter-thymeleaf: For integrating Thymeleaf templates.
o spring-boot-starter-security: For adding security features.

19. What is JPA and how is it used in Spring Boot?

 Answer: JPA (Java Persistence API) is a specification for managing relational data in
Java applications. In Spring Boot, JPA is used for ORM (Object-Relational Mapping)
to interact with databases. Spring Boot automatically configures JPA with the help of
spring-boot-starter-data-jpa.

20. What are the advantages of using Hibernate over JDBC?

 Answer:
o Object Relational Mapping: Hibernate maps Java objects to database tables
automatically, reducing the need for manual SQL queries.
o Performance: Hibernate provides features like caching to improve
performance.
o Database Independence: Hibernate supports various databases, reducing the
dependency on a specific database.
o Transaction Management: Simplifies transaction handling and integrates
easily with Java EE transactions.

21. What is a Servlet in Java?

 Answer: A servlet is a Java class that handles HTTP requests and generates HTTP
responses. It is commonly used to extend the capabilities of web servers by providing
dynamic content such as HTML, JSON, or XML.

22. What are the different types of HTTP requests in Java (GET, POST, PUT,
DELETE)?

 Answer:
o GET: Requests data from a server without modifying it.
o POST: Sends data to the server to create or update a resource.
o PUT: Replaces the current state of the resource with the new data.
o DELETE: Deletes the specified resource from the server.

23. Explain the concept of REST in Java.

 Answer: REST (Representational State Transfer) is an architectural style for


designing networked applications. It uses HTTP methods like GET, POST, PUT,
DELETE for communication. RESTful web services are stateless, scalable, and
client-server based.

24. What is the @RestController annotation in Spring?

 Answer: @RestController is a specialized version of @Controller in Spring that is


used to create RESTful web services. It combines @Controller and @ResponseBody,
meaning the returned values are automatically serialized into JSON or XML.

25. What is the purpose of @RequestMapping in Spring?

 Answer: @RequestMapping is used to map HTTP requests to handler methods of


controllers. It can be used to specify the URL path, request method (GET, POST), and
the parameters of the request.

26. What is @Entity in Hibernate?


 Answer: The @Entity annotation in Hibernate marks a class as an entity that will be
mapped to a database table. Each instance of the entity class represents a row in the
table.

27. Explain the concept of lazy loading in Hibernate.

 Answer: Lazy loading in Hibernate is a technique where an associated entity is


loaded only when it is accessed for the first time, rather than loading it immediately
when the parent entity is loaded. It helps optimize performance by reducing
unnecessary database queries.

28. What is the difference between @OneToMany and @ManyToOne in Hibernate?

 Answer:
o @OneToMany: Defines a one-to-many relationship, where one entity is
associated with multiple instances of another entity.
o @ManyToOne: Defines a many-to-one relationship, where many instances of
one entity are associated with one instance of another entity.

29. What are the different scopes of Spring beans?

 Answer: The different scopes of Spring beans are:


o Singleton: A single instance for the entire Spring container.
o Prototype: A new instance each time it is requested.
o Request: A new bean is created for each HTTP request.
o Session: A new bean is created for each HTTP session.
o Application: A new bean for the entire application context.

30. What is the role of @ComponentScan in Spring?

 Answer: The @ComponentScan annotation is used to specify the base packages for
Spring to scan for components, services, and other beans. It automatically registers
beans marked with @Component, @Service, @Repository, etc., into the application
context.

31. What is the @Transactional annotation in Spring?

 Answer: The @Transactional annotation is used in Spring to manage transactions


declaratively. It ensures that the operations within a method are executed within a
transaction and that the transaction is committed or rolled back based on success or
failure.

32. What is Spring Security and how does it work?

 Answer: Spring Security is a framework that provides authentication, authorization,


and other security features for Java-based applications. It supports securing web
applications, handling login and logout processes, and securing HTTP endpoints using
roles and permissions.
33. What are some common annotations in Spring MVC?

 Answer:
o @Controller: Marks a class as a Spring MVC controller.
o @RequestMapping: Maps HTTP requests to methods in controllers.
o @GetMapping: A shortcut for @RequestMapping(method =
RequestMethod.GET).
o @PostMapping: A shortcut for @RequestMapping(method =
RequestMethod.POST).
o @PathVariable: Binds a method parameter to a URI template variable.
o @RequestParam: Binds request parameters to method arguments.

34. What is the difference between @RequestParam and @PathVariable in Spring?

 Answer:
o @RequestParam: Used to bind request parameters (from query string) to
method parameters.
o @PathVariable: Used to extract values from the URI template (e.g.,
/users/{id}).

35. What is the purpose of @Value in Spring?

 Answer: The @Value annotation in Spring is used to inject values into fields,
methods, or constructor parameters from properties files or other sources. For
example, @Value("${property.name}") injects the value of property.name from
the application properties.

36. What is the role of @Repository annotation in Spring?

 Answer: The @Repository annotation is used to define a Data Access Object (DAO)
in Spring. It is a specialization of @Component and helps Spring to configure the bean
for persistence-related operations and exception translation.

37. What is the difference between @Component and @Service in Spring?

 Answer:
o @Component: A generic annotation for any Spring-managed bean.
o @Service: A specialization of @Component used for service-layer beans. It
doesn't change the functionality but provides a more semantic and readable
context.

38. What is the purpose of @PreAuthorize in Spring Security?

 Answer: The @PreAuthorize annotation in Spring Security is used to define method-


level security. It allows you to specify authorization rules using expressions, such as
role-based access control (hasRole('ADMIN')).

39. Explain the concept of Spring Boot Actuator.


 Answer: Spring Boot Actuator provides built-in endpoints for monitoring and
managing Spring Boot applications. These endpoints expose metrics, health checks,
environment information, and more, which can be accessed over HTTP, JMX, or
other protocols.

40. What is Swagger and how is it used in Spring Boot?

 Answer: Swagger is a tool for documenting and testing RESTful APIs. In Spring
Boot, you can integrate Swagger using the springfox-swagger2 and springfox-
swagger-ui dependencies. It auto-generates interactive API documentation, making
it easier to explore and test endpoints.

41. What is the difference between @RequestMapping and @PostMapping in


Spring?

 Answer:
o @RequestMapping: A more generic annotation for mapping HTTP requests to
handler methods. You can specify the HTTP method type (GET, POST, PUT,
etc.).
o @PostMapping: A shortcut for @RequestMapping(method =
RequestMethod.POST), specifically for POST requests.

42. What is the role of @EnableAutoConfiguration in Spring Boot?

 Answer: @EnableAutoConfiguration tells Spring Boot to automatically configure


beans based on the dependencies in the classpath. It helps eliminate the need for
explicit configuration and promotes convention over configuration.

43. What is the role of @SpringBootApplication in Spring Boot?

 Answer: @SpringBootApplication is a convenience annotation that combines three


annotations: @Configuration, @EnableAutoConfiguration, and @ComponentScan.
It is used to mark the main class of a Spring Boot application.

44. What are the differences between SQL and NoSQL databases?

 Answer:
o SQL: Relational database management systems (RDBMS) like MySQL,
PostgreSQL use structured schemas, tables, and support ACID properties.
o NoSQL: Non-relational databases like MongoDB, Cassandra are schema-less,
support unstructured data, and are highly scalable.

45. Explain the concept of Atomicity in databases.

 Answer: Atomicity ensures that a database transaction is fully completed or not


executed at all. It guarantees that all operations within a transaction are treated as a
single unit, which is either fully committed or rolled back.
46. What is the difference between ArrayList and Vector in Java?

 Answer:
o ArrayList: Implements the List interface, provides dynamic resizing, and is
not synchronized. It is faster when used in single-threaded environments.
o Vector: Implements the List interface, provides dynamic resizing, and is
synchronized. It is slower than ArrayList due to synchronization overhead
but is thread-safe.

47. What are Lambda expressions in Java?

 Answer: Lambda expressions, introduced in Java 8, provide a concise way to


represent an anonymous function (a method without a name). It allows you to pass
behavior as an argument to a method or store behavior in a variable. Example:

(x, y) -> x + y

48. What is a functional interface in Java?

 Answer: A functional interface is an interface with exactly one abstract method,


which can have multiple default or static methods. It is used primarily with Lambda
expressions. Example:

@FunctionalInterface
public interface Calculator {
int add(int a, int b);
}

49. Explain @RequestBody and @ResponseBody in Spring.

 Answer:
o @RequestBody: Used to bind the HTTP request body to a method parameter.
Typically used for POST and PUT requests to accept JSON/XML data.
o @ResponseBody: Indicates that the return value of the method should be
written directly to the HTTP response body (as JSON, XML, etc.).

50. What is Spring Data JPA?

 Answer: Spring Data JPA is a part of the Spring Data project that makes it easier to
implement JPA-based data access layers. It provides repositories for performing
CRUD operations without writing complex queries.

51. What is the purpose of @Query annotation in Spring Data JPA?

 Answer: The @Query annotation in Spring Data JPA allows you to define custom
queries using JPQL or SQL directly in repository methods. This helps when the
default repository methods are not sufficient.

52. What are the advantages of using Spring Boot for building microservices?
 Answer:
o Simplified Configuration: Spring Boot provides auto-configuration for
various components, reducing the setup time.
o Embedded Servers: It comes with embedded servers (like Tomcat or Jetty),
eliminating the need for external web servers.
o Microservice Tools: It integrates with Spring Cloud for building distributed
systems and provides easy ways to handle services like configuration
management, service discovery, and fault tolerance.

53. Explain the concept of Spring Cloud Config.

 Answer: Spring Cloud Config provides server and client support for centralized
external configuration management. It allows external configuration to be stored in a
Git repository, database, or file system and accessed by microservices at runtime.

54. What is the purpose of @Cacheable annotation in Spring?

 Answer: The @Cacheable annotation is used to cache the result of a method so that
subsequent calls with the same parameters can retrieve the result from the cache,
improving performance and reducing redundant computations.

55. What is the difference between synchronized method and ReentrantLock in


Java?

 Answer:
o Synchronized Method: Ensures that only one thread can access a method at a
time, blocking other threads from entering the method.
o ReentrantLock: Provides more flexible thread synchronization than
synchronized. It allows the thread that locks a resource to unlock it
explicitly, and it offers additional features like try-lock and timed lock.

56. What is a REST Controller in Spring?

 Answer: A @RestController is a specialized version of @Controller in Spring,


specifically for creating RESTful APIs. It combines @Controller and
@ResponseBody, so the return values of methods are automatically converted to JSON
or XML and sent to the client.

57. What are some common HTTP status codes?

 Answer:
o 200 OK: Request was successful.
o 201 Created: Resource was successfully created.
o 400 Bad Request: Invalid request from the client.
o 401 Unauthorized: Authentication is required.
o 403 Forbidden: Access is denied.
o 404 Not Found: Resource not found.
o 500 Internal Server Error: An error occurred on the server.
58. What is @Autowired annotation in Spring?

 Answer: The @Autowired annotation is used for automatic dependency injection in


Spring. Spring will automatically inject the required beans into the annotated field,
method, or constructor at runtime.

59. What is the difference between @Service and @Component in Spring?

 Answer:
o @Service: A specialization of @Component used for service-layer beans,
typically for business logic.
o @Component: A generic annotation for any Spring-managed bean.

60. What is the purpose of @EnableAutoConfiguration in Spring Boot?

 Answer: @EnableAutoConfiguration enables Spring Boot's auto-configuration


feature, where it automatically configures the application based on the dependencies
present in the classpath. It simplifies the configuration by automatically configuring
beans and properties.

61. What is Spring Boot DevTools?

 Answer: Spring Boot DevTools provides a set of tools to improve the development
experience. It includes features like automatic restarts, live reload, and configurations
for improved debugging.

62. What is the role of the @PostConstruct annotation in Spring?

 Answer: The @PostConstruct annotation is used to annotate a method that should be


executed after the bean has been initialized and dependencies have been injected. It is
often used for setup or initialization tasks.

63. What is the purpose of @PreDestroy annotation in Spring?

 Answer: The @PreDestroy annotation marks a method to be executed before the


bean is destroyed. It is commonly used for cleanup tasks.

64. What is Spring WebFlux?

 Answer: Spring WebFlux is a reactive programming framework in Spring for


building non-blocking, asynchronous web applications. It is designed to handle large
amounts of concurrent connections with minimal resources by using reactive streams.

65. What is the difference between Spring MVC and Spring WebFlux?

 Answer:
o Spring MVC: It is a synchronous, servlet-based framework that processes
HTTP requests one at a time.
o Spring WebFlux: It is a reactive, asynchronous framework designed for
handling a large number of concurrent requests with non-blocking IO.

66. What is the @RequestMapping annotation used for in Spring?

 Answer: The @RequestMapping annotation is used to map HTTP requests to handler


methods of MVC controllers. It can specify the HTTP method (GET, POST, etc.),
parameters, headers, and path variables for the request.

67. Explain the difference between List, Set, and Map in Java collections.

 Answer:
o List: An ordered collection that can contain duplicate elements (e.g.,
ArrayList, LinkedList).
o Set: An unordered collection that does not allow duplicate elements (e.g.,
HashSet, TreeSet).
o Map: A collection of key-value pairs, where each key is unique, and each key
maps to exactly one value (e.g., HashMap, TreeMap).

68. What is the significance of hashCode() and equals() methods in Java?

 Answer:
o hashCode(): Returns an integer value that represents the memory address or a
hash value of the object.
o equals(): Determines whether two objects are considered equal by
comparing their state. These methods are used by collections like HashSet and
HashMap to store and retrieve objects efficiently.

69. What is the difference between == and equals() in Java?

 Answer:
o ==: Compares the memory addresses of two objects (checks if both reference
the same object).
o equals(): Compares the contents of two objects (checks if the state of the
objects is the same, provided that equals() is overridden).

70. What is a ThreadPoolExecutor in Java?

 Answer: ThreadPoolExecutor is a class in Java that manages a pool of worker


threads, which are used to execute tasks concurrently. It allows you to control the
number of threads executing tasks and provides methods to manage thread lifecycle,
task scheduling, and resource allocation.

71. Explain the concept of garbage collection in Java.

 Answer: Garbage collection is the process of automatically identifying and


reclaiming memory occupied by objects that are no longer in use. Java's garbage
collector (GC) runs in the background, freeing memory for new objects and
preventing memory leaks.

72. What are the different types of garbage collectors in Java?

 Answer:
o Serial GC: Uses a single thread for garbage collection.
o Parallel GC: Uses multiple threads for garbage collection, optimizing
throughput.
o CMS (Concurrent Mark-Sweep) GC: Designed to minimize pause times
during garbage collection.
o G1 (Garbage-First) GC: A low-pause collector designed to meet pause-time
goals.

73. What is the role of ExecutorService in Java?

 Answer: ExecutorService is an interface in Java that provides methods for


managing and controlling thread execution in a concurrent environment. It supports
managing a pool of worker threads and scheduling tasks for execution
asynchronously.

74. What is the use of @EnableWebSecurity in Spring Security?

 Answer: @EnableWebSecurity is used to enable Spring Security's web security


configuration. It ensures that Spring Security is applied to the web layer of the
application, allowing for configuration of HTTP security rules like login, access
control, and CSRF protection.

75. What is the difference between ArrayList and LinkedList in Java?

 Answer:
o ArrayList: Based on a dynamic array, provides fast random access but slower
insertions and deletions compared to LinkedList (due to the need for shifting
elements).
o LinkedList: Based on a doubly-linked list, allows faster insertions and
deletions but slower random access (due to traversal of the list).

76. What is Spring Boot’s application.properties file used for?

 Answer: The application.properties file is used to configure various settings and


properties for a Spring Boot application, such as server port, database configuration,
logging levels, and custom application-specific settings.

77. What is @ResponseStatus in Spring?

 Answer: @ResponseStatus is an annotation in Spring used to mark a method or


exception class with a specific HTTP status code. It is typically used for custom
exception handling, where you can associate an HTTP status code with a particular
exception.
78. Explain the concept of Spring AOP (Aspect-Oriented Programming).

 Answer: Spring AOP is used for separating cross-cutting concerns (like logging,
security, and transaction management) from the business logic of an application. It
allows you to define "aspects" that are applied to methods or classes, such as pre- or
post-execution behavior.

79. What is the difference between @Component, @Service, and @Repository in


Spring?

 Answer:
o @Component: A generic annotation for any Spring-managed bean.
o @Service: A specialization of @Component used for service-layer beans that
contain business logic.
o @Repository: A specialization of @Component used for DAO (Data Access
Object) beans that handle data persistence logic.

80. What is @Transactional annotation in Spring?

 Answer: The @Transactional annotation is used to manage transaction boundaries


in Spring. It ensures that the code inside the annotated method runs within a
transaction, and it handles rollback or commit operations based on success or failure.

81. What is the purpose of @Entity annotation in JPA?

 Answer: The @Entity annotation in JPA marks a class as a JPA entity, which is
mapped to a database table. The class must have an identifier (typically with @Id) and
will be persisted to a relational database.

82. What is @PersistenceContext in Spring Data JPA?

 Answer: @PersistenceContext is used to inject the EntityManager into a Spring


bean. It provides access to the persistence context, allowing interaction with the
database for CRUD operations on entities.

83. Explain the difference between @Autowired and @Inject in Spring.

 Answer:
o @Autowired: A Spring-specific annotation used to inject dependencies
automatically. It can be used with constructors, fields, and methods.
o @Inject: A standard Java annotation (from JSR-330) for dependency
injection, supported by Spring as an alternative to @Autowired.

84. What is the purpose of @Profile annotation in Spring?

 Answer: The @Profile annotation is used to define beans that should only be
available in specific environments or profiles (e.g., development, production). It
allows for conditional bean creation based on the active profile.
85. What is the difference between SessionFactory and EntityManagerFactory in
Spring?

 Answer:
o SessionFactory: The core interface in Hibernate used to create and manage
sessions for interacting with the database.
o EntityManagerFactory: The equivalent in JPA, used to create
EntityManager instances for performing operations on entities.

86. What is the difference between Mono and Flux in Spring WebFlux?

 Answer:
o Mono: Represents a single-value or empty asynchronous operation.
o Flux: Represents a stream of multiple asynchronous values (zero or more).
These are part of the reactive programming model in Spring WebFlux.

87. What is the role of DispatcherServlet in Spring MVC?

 Answer: The DispatcherServlet acts as the front controller in Spring MVC,


responsible for routing incoming HTTP requests to the appropriate handler methods
in controllers. It is the central point of the request-processing lifecycle.

88. What is the difference between @RestController and @Controller in Spring?

 Answer:
o @RestController: Combines @Controller and @ResponseBody. The return
values of its methods are directly written to the HTTP response as
JSON/XML.
o @Controller: Used for handling web pages (e.g., returning views like JSP or
Thymeleaf templates).

89. What are microservices?

 Answer: Microservices is an architectural style where an application is composed of


small, loosely coupled, independently deployable services that communicate over a
network, often using RESTful APIs or messaging.

90. What is Spring Cloud Netflix?

 Answer: Spring Cloud Netflix provides tools for building microservices using Netflix
OSS components like:
o Eureka: Service discovery.
o Ribbon: Client-side load balancing.
o Zuul: API Gateway for routing requests.
o Hystrix: Circuit breaker for fault tolerance.

91. What is the difference between @PathVariable and @RequestParam in Spring?


 Answer:
o @PathVariable: Extracts values from the URI path.
o @RequestParam: Extracts query parameters from the URL. Example:

@GetMapping("/user/{id}")
public String getUser(@PathVariable int id) { ... }

@GetMapping("/user")
public String getUser(@RequestParam String name) { ... }

92. What is a WebSocket?

 Answer: WebSocket is a protocol that enables full-duplex communication between a


client and a server over a single TCP connection. It is commonly used in real-time
applications like chat apps and live notifications.

93. What are the different scopes in Spring beans?

 Answer:
o Singleton: A single instance is created for the entire Spring container (default
scope).
o Prototype: A new instance is created every time the bean is requested.
o Request: A new instance is created for each HTTP request (web applications
only).
o Session: A new instance is created for each HTTP session (web applications
only).
o GlobalSession: A new instance is created for each global HTTP session
(portlet applications only).

94. What is the difference between Serializable and Externalizable in Java?

 Answer:
o Serializable: A marker interface used for default serialization provided by
Java.
o Externalizable: Provides more control over the serialization process by
requiring implementation of writeExternal and readExternal methods.

95. Explain the concept of CORS in web development.

 Answer: CORS (Cross-Origin Resource Sharing) is a mechanism that allows a web


application hosted on one domain to access resources on another domain, subject to
permissions configured in the server's response headers (like Access-Control-
Allow-Origin).

96. What is the purpose of @JsonIgnore in Jackson?

 Answer: The @JsonIgnore annotation is used to exclude a field from being serialized
or deserialized in JSON processing.

97. What is the difference between EntityManager and Hibernate Session?


 Answer:
o EntityManager: A JPA interface for managing entities in a persistence
context.
o Hibernate Session: A Hibernate-specific interface for interacting with the
database and managing entities. The EntityManager internally uses Hibernate
Session in JPA implementations using Hibernate.

98. What are the advantages of using Hibernate over JDBC?

 Answer:
o Provides an abstraction over SQL queries.
o Reduces boilerplate code for database operations.
o Automatic handling of object-relational mapping (ORM).
o Caching mechanisms for improved performance.
o Database-independent.

99. What is the difference between PUT and PATCH HTTP methods?

 Answer:
o PUT: Used to update or replace an existing resource entirely.
o PATCH: Used to partially update an existing resource.

100. What is a DTO in Java?

 Answer: A Data Transfer Object (DTO) is a plain object used to transfer data
between layers or modules of an application without exposing the domain model.

101. What is the purpose of the SpringApplication.run() method in Spring


Boot?

 Answer: The SpringApplication.run() method is the entry point for launching a


Spring Boot application. It starts the embedded server (e.g., Tomcat), initializes the
Spring ApplicationContext, and performs component scanning to configure beans.

102. What is lazy initialization in Spring?

 Answer: Lazy initialization defers the creation of a bean until it is first requested,
rather than during application startup. It improves startup performance and is enabled
using @Lazy or by configuring the application context.

103. Explain the @Value annotation in Spring.

 Answer: The @Value annotation is used to inject values from property files, system
properties, or environment variables into Spring beans. Example:

@Value("${app.name}")
private String appName;
104. What is Spring Boot Actuator?

 Answer: Spring Boot Actuator provides production-ready features like health checks,
metrics, environment information, and application monitoring through REST
endpoints.

105. What is the difference between JOIN and FETCH JOIN in Hibernate?

 Answer:
o JOIN: Used for SQL joins to fetch data from related tables, but it does not
initialize collections or proxies.
o FETCH JOIN: Fetches related entities along with the parent entity, initializing
collections or proxies immediately.

106. What is the purpose of the @Scheduled annotation in Spring?

 Answer: The @Scheduled annotation is used to define scheduled tasks in Spring. It


supports fixed-rate, fixed-delay, and cron-based scheduling.

107. What is the purpose of Spring Boot DevTools?

 Answer: Spring Boot DevTools is a development-time tool that provides features


like automatic application restart, live reload of resources, and property defaults for
faster development.

108. What is the difference between eager and lazy loading in Hibernate?

 Answer:
o Eager Loading: Fetches related entities immediately along with the main
entity.
o Lazy Loading: Delays fetching related entities until they are accessed
explicitly.

109. What is the use of Feign Client in Spring Cloud?

 Answer: Feign Client is a declarative HTTP client in Spring Cloud that simplifies
calling RESTful services. It reduces boilerplate code for REST calls by using
annotations to define interfaces.

110. What are filters and interceptors in a web application?

 Answer:
o Filters: Applied to incoming requests and can manipulate request/response
before reaching the controller (e.g., authentication, logging).
o Interceptors: Spring-specific feature that works at the controller level,
enabling pre- and post-processing of requests.
111. What is the difference between @ComponentScan and
@EnableAutoConfiguration?

 Answer:
o @ComponentScan: Scans specified packages for Spring components (e.g.,
@Component, @Service).
o @EnableAutoConfiguration: Enables auto-configuration of Spring beans
based on classpath dependencies and properties.

112. Explain the difference between checked and unchecked exceptions in


Java.

 Answer:
o Checked Exceptions: Must be declared in the throws clause or handled using
a try-catch block (e.g., IOException).
o Unchecked Exceptions: Subclasses of RuntimeException, not required to be
declared or handled (e.g., NullPointerException).

113. What is the difference between REST and SOAP?

 Answer:
o REST: Lightweight, uses HTTP methods (GET, POST, etc.), and supports
JSON/XML. It is stateless and easy to implement.
o SOAP: Protocol-based, uses XML for communication, and supports features
like security and transactions.

114. What is Spring Data JPA?

 Answer: Spring Data JPA is a Spring module that simplifies database operations
using JPA. It provides repository interfaces, custom query methods, and eliminates
boilerplate code for CRUD operations.

115. What is an Embedded Server in Spring Boot?

 Answer: An embedded server is a server that is bundled with the application,


allowing it to run as a standalone application without requiring external deployment.
Common embedded servers are Tomcat, Jetty, and Undertow.

116. What is WebFlux in Spring?

 Answer: Spring WebFlux is a reactive programming framework for building non-


blocking, asynchronous web applications. It uses reactive streams and supports Mono
and Flux types.

117. What is the purpose of @ExceptionHandler in Spring?


 Answer: The @ExceptionHandler annotation is used to define methods that handle
specific exceptions thrown in a controller. It allows custom error responses for
exceptions.

118. What is the difference between @Transactional(propagation =


Propagation.REQUIRED) and Propagation.REQUIRES_NEW?

 Answer:
o Propagation.REQUIRED: Uses the current transaction or creates a new one if
none exists.
o Propagation.REQUIRES_NEW: Suspends the current transaction and starts a
new one, ensuring isolation.

119. What is JPA Criteria API?

 Answer: JPA Criteria API is a type-safe way to construct dynamic queries in Java. It
avoids SQL injection and allows queries to be built programmatically using Java
objects.

120. What are Lombok annotations, and why are they used?

 Answer: Lombok is a Java library that reduces boilerplate code by generating getters,
setters, constructors, and other methods at compile time using annotations like
@Getter, @Setter, @Data, and @Builder.

121. What is the difference between @ControllerAdvice and


@RestControllerAdvice in Spring?

 Answer:
o @ControllerAdvice: Used to handle exceptions and provide common
functionality for controllers. It works across all controllers in the application.
o @RestControllerAdvice: A combination of @ControllerAdvice and
@ResponseBody, specifically for REST APIs, ensuring responses are serialized
to JSON or XML.

122. What is an API Gateway in microservices architecture?

 Answer: An API Gateway acts as a single entry point for client requests in a
microservices architecture. It handles request routing, authentication, load balancing,
and other cross-cutting concerns. Tools like Spring Cloud Gateway and Zuul are
popular implementations.

123. What is the @PathParam annotation in JAX-RS?


 Answer: The @PathParam annotation in JAX-RS is used to bind URI path parameters
to method parameters. For example:

@GET
@Path("/user/{id}")
public String getUser(@PathParam("id") int id) {
return "User ID: " + id;
}

124. Explain HATEOAS in RESTful web services.

 Answer: HATEOAS (Hypermedia As The Engine Of Application State) is a


constraint of RESTful web services where the client interacts with a service using
hypermedia links provided in the response. This helps discover available actions
dynamically.

125. What is Spring Security?

 Answer: Spring Security is a framework that provides authentication, authorization,


and protection against common attacks like CSRF, XSS, and SQL injection. It
integrates easily with Spring applications.

126. What is the use of Spring Retry?

 Answer: Spring Retry provides an abstraction for retrying operations in case of


failure. It supports features like customizable retry policies, backoff strategies, and
exception handling.

127. What is the difference between Callable and Runnable in Java?

 Answer:
o Runnable: Represents a task that does not return a result and cannot throw
checked exceptions.
o Callable: Represents a task that returns a result and can throw checked
exceptions.

128. What is the @ModelAttribute annotation in Spring MVC?

 Answer: The @ModelAttribute annotation is used to bind request parameters to


model attributes or to populate model attributes for views. It is typically used in form
handling.
129. What is the difference between HttpSession and SessionAttributes in
Spring?

 Answer:
o HttpSession: Represents an HTTP session and is used to store data across
multiple requests.
o @SessionAttributes: Used to store model attributes in the session for use
across multiple requests within the same session.

130. What is Spring’s WebClient?

 Answer: WebClient is a reactive, non-blocking client in Spring WebFlux used to


perform HTTP requests. It is the replacement for RestTemplate in reactive
applications.

131. What is OAuth 2.0?

 Answer: OAuth 2.0 is an open standard for authorization that allows applications to
access resources on behalf of a user without sharing their credentials. It provides
various flows for different use cases, such as authorization code, client credentials,
and password grants.

132. What are the different types of dependency injection in Spring?

 Answer:
o Constructor Injection: Dependencies are provided through a class
constructor.
o Setter Injection: Dependencies are provided via setter methods.
o Field Injection: Dependencies are injected directly into fields using
@Autowired.

133. What is the difference between POST and PUT HTTP methods?

 Answer:
o POST: Used to create a new resource.
o PUT: Used to update or replace an existing resource, or create a resource if it
does not exist.
134. What is the purpose of the @CrossOrigin annotation in Spring?

 Answer: The @CrossOrigin annotation enables Cross-Origin Resource Sharing


(CORS) for a specific controller or method, allowing requests from different domains.

135. What is the difference between Optional.of() and Optional.ofNullable()?

 Answer:
o Optional.of(): Throws a NullPointerException if the value is null.
o Optional.ofNullable(): Returns an empty Optional if the value is null.

136. What is the default scope of a Spring bean?

 Answer: The default scope of a Spring bean is singleton, meaning only one instance
of the bean is created per Spring container.

137. What is a Proxy object in Spring AOP?

 Answer: A Proxy object is a dynamically generated object that intercepts method


calls to the target object. It is used to implement cross-cutting concerns like logging,
security, and transactions.

138. What is the difference between Map, HashMap, and ConcurrentHashMap?

 Answer:
o Map: An interface representing a key-value pair collection.
o HashMap: A non-thread-safe implementation of Map.
o ConcurrentHashMap: A thread-safe implementation of Map that allows
concurrent reads and writes.

139. What is the purpose of Thymeleaf in Spring Boot?

 Answer: Thymeleaf is a server-side Java template engine used for rendering dynamic
views in web applications. It integrates seamlessly with Spring MVC.

140. What is a Circuit Breaker in microservices?


 Answer: A Circuit Breaker is a design pattern used to prevent service failures from
cascading by monitoring service calls and stopping requests when a failure threshold
is reached. Tools like Resilience4j and Hystrix are used to implement it.

141. What is the difference between @RequestBody and @ResponseBody in Spring?

 Answer:
o @RequestBody: Maps the incoming HTTP request body to a Java object.
o @ResponseBody: Converts the return value of a controller method to the HTTP
response body in JSON or XML format.

142. What is the difference between Servlet and Filter in Java?

 Answer:
o Servlet: Processes HTTP requests and generates responses. It acts as a
controller in web applications.
o Filter: Intercepts and modifies requests and responses before they reach the
servlet. It is used for tasks like authentication, logging, or input validation.

143. What is the difference between String, StringBuilder, and StringBuffer in


Java?

 Answer:
o String: Immutable, meaning its value cannot be changed once created.
o StringBuilder: Mutable and not thread-safe, suitable for single-threaded
applications.
o StringBuffer: Mutable and thread-safe, designed for multi-threaded
environments.

144. What is Spring Batch?

 Answer: Spring Batch is a framework for processing large volumes of data in batch
jobs. It supports features like transaction management, chunk-based processing,
parallel execution, and retry mechanisms.

145. What is the difference between @Component, @Service, and @Repository in


Spring?

 Answer:
o @Component: Generic stereotype for Spring components.
o @Service: Specialization of @Component for service-layer beans.
o @Repository: Specialization of @Component for persistence-layer beans,
enabling exception translation.

146. What is the purpose of the @Transactional annotation in Spring?

 Answer: The @Transactional annotation manages transactions in Spring. It ensures


that a set of database operations are executed as a single unit and supports features
like rollback and isolation levels.

147. What is a DTO, and how is it different from an Entity?

 Answer:
o DTO (Data Transfer Object): Used to transfer data between layers, often
containing only required fields.
o Entity: Represents a database table, typically used with ORM frameworks like
Hibernate.

148. What is the difference between a thread pool and a single thread in Java?

 Answer:
o Thread Pool: Manages a pool of threads to handle multiple tasks
concurrently, reducing the overhead of thread creation and destruction.
o Single Thread: Executes one task at a time and does not support parallel
processing.

149. What is Eureka in Spring Cloud?

 Answer: Eureka is a service discovery tool from Netflix OSS. It allows microservices
to register themselves and discover other services for communication.

150. What is the purpose of @EnableEurekaClient in Spring Boot?

 Answer: The @EnableEurekaClient annotation registers a microservice with a


Eureka server so it can be discovered by other services.
151. What is the difference between Mono and Flux in Spring WebFlux?

 Answer:
o Mono: Represents a single asynchronous value or no value.
o Flux: Represents a stream of zero, one, or many asynchronous values.

152. What is the difference between HashSet and TreeSet?

 Answer:
o HashSet: Stores elements in an unordered manner and allows null values.
o TreeSet: Stores elements in sorted order and does not allow null values.

153. What is Feign in microservices?

 Answer: Feign is a declarative HTTP client in Spring Cloud that simplifies making
RESTful service calls by defining interfaces annotated with REST annotations.

154. What is the purpose of @Cacheable in Spring?

 Answer: The @Cacheable annotation caches the result of a method so that subsequent
calls with the same arguments return the cached value instead of executing the
method.

155. What is the @RequestMapping annotation in Spring?

 Answer: The @RequestMapping annotation maps HTTP requests to specific handler


methods in a controller. It supports various attributes like value, method, headers,
etc.

156. What is the Fork/Join Framework in Java?

 Answer: The Fork/Join Framework is a parallel computing framework in Java that


splits tasks into smaller subtasks (fork) and then combines their results (join). It is part
of the java.util.concurrent package.

157. What is the difference between Comparator and Comparable?


 Answer:
o Comparable: Defines a natural ordering for objects via the compareTo()
method.
o Comparator: Allows custom ordering for objects via the compare() method.

158. What is a Load Balancer in microservices?

 Answer: A Load Balancer distributes incoming requests across multiple instances of


a service to ensure high availability and scalability. Ribbon and Spring Cloud
Gateway are common examples.

159. What is the ExecutorService in Java?

 Answer: The ExecutorService is a high-level API in Java that provides thread pool
management and simplifies concurrent task execution.

160. What is a Circuit Breaker in microservices?

 Answer: A Circuit Breaker prevents service failures from cascading by monitoring


service calls and breaking the circuit (stopping calls) when a failure threshold is
reached. Tools like Hystrix and Resilience4j implement this pattern.

You might also like