Full Stack Java Ques
Full Stack Java Ques
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.
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.
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.
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.
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.
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.
17. What is Spring Boot and how is it different from the traditional Spring
framework?
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.
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.
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.
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.
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.
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.
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.
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}).
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.
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.
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.
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.
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.
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.
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.
(x, y) -> x + y
@FunctionalInterface
public interface Calculator {
int add(int a, int b);
}
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.).
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.
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.
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.
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.
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.
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:
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.
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.
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.
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).
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.
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).
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.
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).
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.
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.
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.
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.
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.
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).
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.
@GetMapping("/user/{id}")
public String getUser(@PathVariable int id) { ... }
@GetMapping("/user")
public String getUser(@RequestParam String name) { ... }
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).
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.
Answer: The @JsonIgnore annotation is used to exclude a field from being serialized
or deserialized in JSON processing.
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.
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.
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.
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.
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.
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.
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.
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).
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.
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.
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.
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.
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.
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.
@GET
@Path("/user/{id}")
public String getUser(@PathParam("id") int id) {
return "User ID: " + id;
}
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.
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.
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.
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:
o Optional.of(): Throws a NullPointerException if the value is null.
o Optional.ofNullable(): Returns an empty Optional if the value is null.
Answer: The default scope of a Spring bean is singleton, meaning only one instance
of the bean is created per Spring container.
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.
Answer: Thymeleaf is a server-side Java template engine used for rendering dynamic
views in web applications. It integrates seamlessly with Spring MVC.
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.
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.
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.
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.
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.
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.
Answer: Eureka is a service discovery tool from Netflix OSS. It allows microservices
to register themselves and discover other services for communication.
Answer:
o Mono: Represents a single asynchronous value or no value.
o Flux: Represents a stream of zero, one, or many asynchronous values.
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.
Answer: Feign is a declarative HTTP client in Spring Cloud that simplifies making
RESTful service calls by defining interfaces annotated with REST annotations.
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.
Answer: The ExecutorService is a high-level API in Java that provides thread pool
management and simplifies concurrent task execution.