1. Why should you use Spring Boot?
● Ease of Setup: Simplifies app setup with sensible defaults and auto-configuration,
reducing boilerplate code.
● Microservices Support: Works seamlessly with Spring Cloud for microservices,
integrating easily with Docker, Kubernetes, etc.
● Standalone Applications: Packages apps as self-contained JAR/WAR files, eliminating
the need for an external server.
● Embedded Servers: Includes embedded servers like Tomcat, Jetty, and Undertow,
simplifying deployment.
● Cloud-Native: Optimized for cloud platforms and distributed systems, making it easy to
build scalable apps.
● Rich Ecosystem: Integrates with Spring projects (Data, Security, Batch) to solve various
development challenges.
● Production-Ready Features: Built-in health checks, metrics, logging, and configuration
for production management.
● Large Community & Documentation: Extensive community support and
comprehensive, regularly updated documentation.
2. What are the differences between Spring and Spring Boot?
● Spring requires manual configuration and external server setup.
● Spring Boot offers auto-configuration, embedded servers, and starter dependencies for
quicker development.
3. What is Spring Boot and the need for it?
Spring Boot is a framework that simplifies the development of Java-based applications, built on
top of the Spring framework. It reduces the amount of boilerplate code and configuration,
allowing developers to focus more on business logic.
Key Features:
1. Auto Configuration: Automatically configures the app based on dependencies.
2. Standalone Apps: Allows apps to run independently with embedded servers like
Tomcat.
3. Microservices Ready: Ideal for building scalable microservices.
4. Production-Ready: Provides built-in features for health checks, metrics, and logging.
5. Minimal Configuration: Reduces the need for complex XML or Java configurations.
6. Embedded Servers: Includes Tomcat, Jetty, etc., for easier deployment.
Need for Spring Boot:
● Faster Development: Reduces setup time with automatic configurations.
● Simplifies Configuration: Less manual setup compared to traditional Spring apps.
● Microservices and Cloud Integration: Great for building and deploying microservices.
● Production-Ready: Built-in monitoring and health features for easier maintenance.
● Consistent Development: Standardizes Java development across projects
4. Advantages of Spring Boot:
● Simplified Setup and Configuration
● Faster Development
● Embedded Servers
● Microservices Ready
● Production-Ready Features
● Minimal Boilerplate Code
● Easy Dependency Management
● Active Community and Ecosystem
● Scalability and Flexibility
● Cross-Platform Compatibility
5. Features of Spring Boot:
● Auto Configuration: Automatically configures the app based on dependencies.
● Standalone Apps: Allows apps to run independently with embedded servers like
Tomcat.
● Microservices Ready: Ideal for building scalable microservices.
● Production-Ready: Provides built-in features for health checks, metrics, and logging.
● Minimal Configuration: Reduces the need for complex XML or Java configurations.
● Embedded Servers: Includes Tomcat, Jetty, etc., for easier deployment
6. How to create a Spring Boot application using Maven?
● Use Spring Initializr (https://start.spring.io/) to generate the base project with Maven
and dependencies.
● Alternatively, create pom.xml manually, Add Spring Boot Dependency to pom.xml
● Create a Main Application Class(@SpringBootApplication)
The @SpringBootApplication annotation is a combination of:
@Configuration (for configuration),
@EnableAutoConfiguration (for auto configuration),
@ComponentScan (for scanning components in the current package and its sub-packages)
● Add a Controller (@RestController)
● Run the Application (mvn spring-boot:run)
● Verify the Application :Open your web browser and navigate to
http://localhost:8080/.
7. What are the possible sources of external configuration?
● application.properties/yml: Default and most common.
● Command-line arguments: Override properties at runtime.
● Environment variables: Set at the OS or container level.
● Profile-specific properties: Configuration for different environments.
● JNDI: For container-managed environments.
● Spring Cloud Config: Centralized configuration server for microservices.
● Cloud provider configurations: Managed by cloud services (AWS, GCP, etc.).
● External files: For configurations outside the application.
● System properties: Passed using -D flag in JVM.
● Git repositories: Manage configurations in version-controlled systems.
8. What happens in the background when a Spring Boot app "runs as a
Java application"?
● JVM starts and invokes the main() method.
● SpringApplication.run() triggers the Spring Boot initialization.
● Auto-configuration detects dependencies and sets up the application context.
● Component scanning discovers and registers beans.
● Embedded server starts if it’s a web application (e.g., Tomcat).
● ApplicationContext is created, and beans are injected with dependencies.
● The application becomes ready to process requests (web) or execute tasks (non-web).
● It stays alive and handles requests or operations until stopped.
9. What are Spring Boot starters and what are the available starters?
● Spring Boot Starters are a set of pre-configured, reusable dependencies that help you
quickly add specific functionality to your Spring Boot application.
Examples:
● Web applications: spring-boot-starter-web,
spring-boot-starter-thymeleaf
● Database and JPA: spring-boot-starter-data-jpa,
spring-boot-starter-jdbc
● Security: spring-boot-starter-security
● Testing: spring-boot-starter-test
● Actuator/Monitoring: spring-boot-starter-actuator
● Messaging: spring-boot-starter-amqp
● Caching: spring-boot-starter-cache
● Mail support: spring-boot-starter-mail
10. Explain Spring Actuators and its advantages:
● Spring Boot Actuator is a set of built-in tools provided by Spring Boot that enables you
to monitor and manage your application in production. It adds production-ready features
to your Spring Boot application, such as health checks, metrics, application information,
and environment details.
Advantages of Spring Boot Actuator
1. Production-Ready Features:
Provides essential endpoints for health checks, metrics, logging, and more, making it
easier to monitor and manage applications in production.
2. Health Monitoring:
The /actuator/health endpoint enables automated health checks, useful for
systems like Kubernetes or Docker Swarm.
3. Centralized Metrics:
The /actuator/metrics endpoint provides a centralized way to monitor key
application metrics such as memory usage and response times.
4. Customizable:
Allows the creation of custom health checks and metrics, tailoring the monitoring to the
application's specific needs.
5. Dynamic Logging Management:
You can change log levels at runtime without restarting the application, aiding
troubleshooting in production.
6. Improved Observability:
Actuator integrates with monitoring tools like Prometheus and Grafana, enhancing the
observability of your application.
7. Security and Auditing:
Provides auditing capabilities to track critical system events like login attempts and
authentication failures.
8. Easy Integration with External Tools:
Actuator endpoints integrate easily with monitoring, logging, and alerting systems like
Prometheus, ELK Stack, and Grafana.
9. Simplifies Troubleshooting:
Provides detailed insights like thread dumps and application health data, helping identify
and resolve issues faster.
10.Minimal Configuration:
Comes pre-configured with useful endpoints, requiring minimal setup for monitoring and
management.
11. What is Spring Boot dependency management?
Spring Boot Dependency Management simplifies the process of managing libraries and
versions in a Spring Boot application. It uses starters, BOMs, and automatic version control to
ensure compatibility and reduce configuration overhead, allowing developers to focus on
application development rather than dependency management.
● Starter Dependencies: Pre-configured libraries for common tasks (e.g.,
spring-boot-starter-web, spring-boot-starter-data-jpa)
● Version Management: Automatically handles library versions via BOM (Bill of Materials)
● Transitive Dependencies: Manages dependencies of dependencies, so you don’t have
● Exclusions: Allows excluding specific transitive dependencies when necessary
● Minimal Configuration: Reduces the need for specifying versions manually
● Compatibility: Ensures compatibility across all dependencies and versions
12. Minimum requirements for a Spring Boot system?
● JDK 8+
● Maven/Gradle (optional for building)
● A simple Spring Boot application
● IDE (optional but helpful)
● Internet connection for dependencies
● Minimum system resources: 2GB RAM, disk space as needed
13. What is Thymeleaf and how to use it?
● Thymeleaf is a modern server-side Java template engine used for rendering dynamic
web pages. It is primarily used with Spring Boot applications to generate HTML content,
allowing you to create views (templates) that are rendered by the server
● Add Thymeleaf Dependency
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
14. Can we change the port of the embedded Tomcat server in Spring
Boot?
● Yes, by setting server.port in application.properties (e.g.,
server.port=8081).
● Using command-line arguments like --server.port
15. Need for Spring Boot DevTools:
● Spring Boot DevTools provides hot swapping, automatic restarts,Remote Debugging
Fast and Efficient Development Cycle,Disable DevTools in Production,Configuration
Caching and enhanced logging to speed up development.
16. Steps to create a Spring Boot project using Spring Initializr:
● Go to https://start.spring.io/.
● Select your project settings (Maven/Gradle, Java version, dependencies).
● Click Generate to download the .zip file.
● Extract the project and open it in your IDE.
● Run the project from your IDE or via the command line.
● Access the application at http://localhost:8080..
17. Steps to connect Spring Boot to a database using JDBC:
● Add dependencies: Include spring-boot-starter-jdbc and the appropriate JDBC
driver for your database.
● Configure database connection: Define the connection properties in
application.properties or application.yml.
● Configure DataSource (optional): Spring Boot auto-configures the DataSource, but
you can also configure it manually.
● Create JdbcTemplate: Set up JdbcTemplate for interacting with the database.
● Create Service or Repository: Write business logic using JdbcTemplate to query and
manipulate the database.
● Test: Test your connection by running the application and verifying database
interactions.
18. How to enable HTTP/2 support in Spring Boot?
HTTP/2 is the second major version of the HTTP protocol, designed to improve web
performance, especially in reducing latency
Use an embedded web server (Tomcat 8.5+, Jetty 9.4+, or Undertow 2.x).
Enable SSL/TLS since HTTP/2 requires secure connections.
Add the following properties to your application.properties or application.yml:
● server.ssl.enabled=true to enable SSL.
● server.http2.enabled=true to enable HTTP/2.
Generate and configure SSL certificates (self-signed or from a CA).
Verify that HTTP/2 is enabled by checking the response headers or using a browser
developer tool or cURL.
19. What are @RequestMapping and @RestController annotations used
for?
● @RequestMapping: Used to map HTTP requests to handler methods of MVC
controllers.
● @RestController: A convenience annotation combining @Controller and
@ResponseBody, returning data directly as JSON/XML.
20. What is Spring Boot CLI?
● Spring Boot CLI allows running Groovy-based Spring Boot applications directly from the
command line without building a WAR/JAR file.
21. Difference between JPA and Hibernate:
● JPA is a specification for ORM, while Hibernate is a popular implementation of JPA.
22. How to create a custom endpoint in Spring Boot Actuator?
● Step 1: Add the Spring Boot Actuator dependency.
● Step 2: Define a custom endpoint class using @Endpoint and annotate methods with
@ReadOperation, @WriteOperation, etc.
● Step 3: Enable the custom endpoint by including it in the
management.endpoints.web.exposure.include property.
● Step 4: Access the custom endpoint via
http://localhost:8080/actuator/customstatus.
● Optional Step: Add additional operations or secure your custom endpoint.
23. What do you understand by Spring Data?
● Spring Data simplifies database interactions by providing a unified framework for
working with various data stores.
● It reduces the boilerplate code required for data access by offering automated CRUD
operations, custom queries, and integration with various data sources such as JPA,
MongoDB, Cassandra, and others.
● It also includes advanced features like paging, sorting, auditing, and transaction
management, making it easier for developers to build scalable and maintainable
applications.
24. What is auto-configuration in Spring Boot and how to disable it?
● Auto-configuration automatically configures your application based on the
dependencies in the classpath. It can be disabled with
@EnableAutoConfiguration(exclude = {YourClass.class}).
25. Difference between @SpringBootApplication and
@EnableAutoConfiguration?
● @SpringBootApplication is a convenience annotation that includes
@EnableAutoConfiguration, @ComponentScan, and @Configuration.
@EnableAutoConfiguration is responsible for auto-configuring the application.
26. Steps to deploy a Spring Boot web application as JAR/WAR?
● For JAR: Package the application with spring-boot-maven-plugin and run it with
java -jar.
● For WAR: Configure @SpringBootApplication as a WAR deployment and package
it with spring-boot-maven-plugin as a WAR.
27. Example for ReadOnly = true in transaction management:
● Annotate methods with @Transactional(readOnly = true) to make them
read-only, optimizing for queries.
● transaction will not involve any data modifications (e.g., no INSERT, UPDATE, or DELETE
operations)
28. Deploying to a different server with Spring Boot:
● JAR Deployment: If you're deploying to a standalone server or a server with an
embedded web server, you can deploy the JAR file and simply run it using java -jar.
● WAR Deployment: If you're deploying to a traditional servlet container (e.g., Apache
Tomcat), you package the app as a WAR file, and deploy it by copying it to the server's
deployment directory.
● Cloud Deployment: You can easily deploy to cloud platforms like Heroku, AWS,
Google Cloud, and Azure using their respective deployment tools (e.g., gcloud,
heroku CLI).
29. Best way to expose custom application configuration with Spring Boot:
● Use application.properties, application.yml, or externalized configuration
with profiles for environment-specific settings.
30. Can we create a non-web application in Spring Boot?
● Yes, by using the @SpringBootApplication annotation without web dependencies,
creating a command-line application or a batch job.
31. Steps to connect an external database (MySQL/Oracle):
● Add the appropriate JDBC driver to dependencies.
● Configure database details in application.properties.
● Use Spring Data JPA or JdbcTemplate for database operations.
32. Advantage of YAML over properties files and how to load it in Spring
Boot?
Advantages of YAML:
● Better readability due to its structured and hierarchical format.
● Supports nested data and complex data structures like arrays and objects.
● Comments are easier to manage, making the configuration file more maintainable.
● YAML is compatible with a variety of tools (e.g., Docker, Kubernetes), which is useful for
cloud-based or containerized environments.
How to Load YAML in Spring Boot:
1. Place application.yml or application.yaml in src/main/resources.
2. Spring Boot automatically loads the YAML file at startup.
3. Access properties using @Value or @ConfigurationProperties annotations.
33. How is Hibernate chosen as the default implementation for JPA without
any configuration?
● Hibernate is the default JPA implementation in Spring Boot because it’s included as a
transitive dependency in the spring-boot-starter-data-jpa starter.
● Auto-configuration in Spring Boot automatically detects the presence of Hibernate and
configures it as the JPA provider.
● There is no need for additional configuration to use Hibernate, but if you prefer another
JPA provider, you can exclude Hibernate and include the alternative provider in the
classpath.
34. What is Spring Data REST?
● Spring Data REST automatically exposes Spring Data repositories as RESTful web
services.
● No need for manual controllers: The framework automatically generates CRUD
operations for your entities.
● HATEOAS support: The responses include links to related resources.
● Customizable: You can customize endpoints using annotations like
@RepositoryRestResource and create custom queries.
● Integration with Spring Data: It works seamlessly with Spring Data repositories,
including JPA, MongoDB, and other data stores.
35. Difference between RequestMapping and GetMapping?
36. Where should the boundary of a transaction start?
● The transaction boundary should start at the beginning of a business operation in the
service layer, where multiple actions are performed on data that must be treated as a
single unit. This ensures that all changes are atomic, consistent, isolated, and durable
(ACID principles)
37. How does path=”sample”, collectionResourceRel=”sample” work with
Spring Data REST?
● path controls the URL path for the collection of entities.
● collectionResourceRel controls the name of the collection resource in the
HATEOAS response
38. How to register custom auto-configuration?
● Create a custom configuration class with @Configuration and use
@EnableAutoConfiguration or @SpringBootApplication.
● Create a custom auto-configuration class annotated with @Configuration.
● Register the auto-configuration class in META-INF/spring.factories under
org.springframework.boot.autoconfigure.EnableAutoConfiguration.
● Use @ConditionalOnProperty or other conditional annotations to control when
the auto-configuration should be applied.
● Package and distribute the configuration as a JAR to be used by other Spring Boot
applications.
39. How do you configure Log4j for logging?
● Exclude Logback and include Log4j2 dependencies in your pom.xml or
build.gradle file.
● Create a log4j2.xml configuration file in the src/main/resources folder to
define appenders and loggers.
● Configure log levels in application.properties or application.yml (optional).
● Test the configuration by logging messages in your services or controllers.
● Verify that Log4j2 is being used by checking the log output during startup.
40. Difference between WAR and embedded containers:
41. Need for profiles:
● In Spring Boot, profiles are a powerful feature that allows you to define different
configurations and settings for different environments (e.g., development, testing,
production)
● Separation of Concerns: Keeps environment-specific code and configurations separate
from the main application.
● Simplified Testing: Easily switch to test configurations for unit or integration tests.
● Cleaner and Scalable Code: Avoids hardcoding different configurations in the
application.
● Easy Deployment: Easily manage environment-specific configurations without
modifying application code when deploying to different environments.
42. Steps to add custom JS code in Spring Boot?
● Create the static folder: src/main/resources/static/ if it doesn't exist.
● Add your custom JavaScript file: Place it in static/js/ (e.g., custom.js).
● Reference the JS file in your HTML: Use the <script> tag with the correct path.
● Run your Spring Boot application and test your JS code.
43. How to instruct an auto-configuration to back off when a bean exists?
● Use @EnableAutoConfiguration(exclude = {YourBean.class}) to prevent
specific auto-configurations from applying.
44. Why Spring Data REST is not recommended in real-world applications?
● It exposes your entire database model via REST, which can lead to security and
performance issues if not carefully controlled.
45. Error when H2 is not in the classpath?
● You may see an error like java.lang.ClassNotFoundException:
org.h2.Driver.
46. Use profiles to configure environment-specific settings?
● Use application-{profile}.properties or application.yml to configure
different settings for each profile.
47. Dependencies needed to start a JPA application with Spring Boot?
● Add spring-boot-starter-data-jpa and a database driver like H2, MySQL, or
PostgreSQL in your pom.xml.
48. Spring Boot supports relaxed binding?
● Spring Boot allows flexible property binding, where myProperty can be set as
my-property or my.property.
49. Where is database connection info specified for automatic H2
connection?
● It’s in application.properties with properties like
spring.datasource.url=jdbc:h2:mem:testdb.
50. Default name of H2 database in Spring Boot?
● The default name is testdb.
51. Can we use Jetty instead of Tomcat?
● Yes, by adding spring-boot-starter-jetty and excluding
spring-boot-starter-tomcat.
52. You need to prevent API abuse by implementing a rate limiter in
springboot
1. How would you implement it
2. Which algorithm would you use (Token bucket VS Leaky Bucket)
3. How can redis help in rate limiting
You can implement rate limiting in Spring Boot using different techniques. A common and
efficient way is to use Redis, which acts as a distributed data store for managing rate limit
counters.
1. Rate Limiting Algorithms: Token Bucket vs Leaky Bucket
There are two main algorithms to handle rate limiting: Token Bucket and Leaky Bucket. Here's
a comparison:
Token Bucket Algorithm:
● How it works:
○ Tokens are added to the bucket at a fixed rate (e.g., 1 token per second). Each
API request consumes 1 token. If there are no tokens left, the request is denied.
○ The token bucket allows bursts of traffic, but the average rate is controlled.
● Pros:
○ More flexible, allowing bursts of requests (e.g., multiple requests at once).
○ Ensures that a certain number of requests can happen quickly, followed by a
rate-limited period to avoid abuse.
Leaky Bucket Algorithm:
● How it works:
○ Requests are added to the bucket. The bucket leaks at a fixed rate (e.g., 1
request per second). If the bucket overflows (i.e., requests exceed the capacity),
the excess requests are rejected.
○ It enforces a more consistent, smooth request rate without bursts.
● Pros:
○ More predictable, with a constant request rate.
○ Prevents sudden bursts, ensuring consistent usage of the API.
Which Algorithm to Choose?
● Token Bucket is often the preferred choice when you want to allow burst traffic but still
control the overall rate of requests (i.e., users can make requests quickly when allowed
but won't exceed the overall rate limit).
● Leaky Bucket is better if you want a smooth, steady rate of requests, without allowing
spikes.
In practice, for rate limiting API traffic where bursts are common but should still be controlled,
Token Bucket is often used.
Rate Limiting Algorithms:
● Token Bucket is more flexible, allowing bursts of requests, while Leaky Bucket is
smoother and enforces a steady rate of requests.
Redis for Rate Limiting:
● Redis stores rate limit counters (tokens or request counts) and expiration times, which
allows for distributed, fast, and efficient rate limiting.
Implementation:
● Use Token Bucket or Leaky Bucket algorithm with Redis to track requests, refill tokens,
and enforce limits.
Redis Advantage:
● Redis is ideal for distributed rate limiting due to its fast, in-memory nature and support for
atomic operations and key expiration.
53. Your system expects 1M+ requests per second during peak load
1. How do you scale your system
2. What caching mechanism would you implement ?
3. How do you handle sudden traffic spikes?
System Scaling:
● Use horizontal scaling with microservices and auto-scaling.
● Employ distributed databases and sharding to ensure database scalability.
● Use load balancing to distribute traffic and ensure high availability.
Caching Mechanism:
● Use Redis or Memcached for in-memory caching to reduce load on databases.
● Use CDNs for static content to offload traffic and improve latency.
● Implement cache eviction policies (e.g., LRU, TTL) to manage cache efficiently.
Handling Sudden Traffic Spikes:
● Implement auto-scaling and load balancing to handle spikes dynamically.
● Use API rate limiting to control excessive requests and prevent abuse.
● Employ asynchronous processing with queues for background tasks.
● Implement circuit breakers to prevent cascading failures.
● Use backpressure handling and CDNs to manage load effectively during high-traffic
periods.
54. Users are uploading large files (1GB+) and the service is slowing down
1. What’s the best way to handle file upload efficiently
2. Would you use S3, MinIO, or other storage solution?
3. How to implement a resumable upload
Best Way to Handle Large File Uploads:
● Use chunked uploads to split large files into manageable parts and upload them
asynchronously.
● Implement resumable uploads to allow users to pause and resume uploads if network
issues occur.
Storage Solutions:
● Amazon S3 is a highly reliable, scalable solution, perfect for storing large files with
multipart uploads and resumable upload support.
● MinIO is a self-hosted alternative that offers S3 API compatibility and is a good option if
you want to control your infrastructure.
● Other Cloud Providers like Google Cloud Storage or Azure Blob Storage also offer
similar features.
Resumable Upload Implementation:
● Use multipart uploads for server-side storage (S3/MinIO) to allow efficient and
resumable uploads.
● For client-side, use libraries like Resumable.js or Plupload to handle chunking, retries,
and resumption of uploads.
55. Fix the memory leak
1. What is wrong with this code
2. How do you fix the memory leak?
Class MemoryleakExample{
Private static List<string> cache = new ArrayList<>();
Public void addData(){
for(int i=0; i<1000000; i++){
cache.add(“Data-”+i);
}}}
To fix the memory leak in the MemoryleakExample class, we need to address the growing
memory consumption caused by continuously adding data to the cache list without releasing
memory.
Issue:
In the current code:
● A static List<String> (cache) is used to store a large number of strings.
● The method addData() adds 1 million strings to the cache every time it is called, but
never clears the list, which can cause the JVM to run out of memory, especially after
repeated method calls.
Solutions to Fix the Memory Leak:
● Remove Unused Data
● Use Weak References
● Clear the Cache
● Use a More Efficient Data Structure(e.g., LinkedHashMap with a size limit)
56. Your rest API is slow , fix the code
1. Why is this method slow for large datasets
2. How can you optimize it using pagination?
@GetMapping (“/Users”)
Public List<users> getAllusers(){
Return userRespository.findAll();
The method in your REST API is slow for large datasets because it is retrieving all the records
from the database using userRepository.findAll()
Steps to Implement Pagination:
1.Modify the getAllUsers() method to accept pagination parameters
(such as page number and page size).
2.Use PageRequest to provide pagination information.
3.Return a Page object from the repository, which contains the
results and metadata (e.g., total records, total pages).
57. What is Maven and what problem does it solve?
● Maven is a build automation tool used primarily for Java projects. It simplifies project
setup, dependency management, and build processes.
● Problem Solved: It solves the problem of managing dependencies (libraries,
frameworks), automating builds (compiling, packaging, testing), and managing project
configurations in a standard way.
58. What is a POM file?
● POM stands for Project Object Model. It is an XML file (pom.xml) that contains
configuration information for Maven projects.
● It defines the project structure, dependencies, plugins, and goals (build lifecycle). It
serves as the core configuration file for a Maven project.
59. What is a dependency in Maven?
● A dependency in Maven refers to an external library or framework that your project
needs in order to compile or run. Maven automatically downloads and includes these
dependencies in your project based on the configurations specified in the pom.xml file.
60. What is the Maven repository?
● A Maven repository is a storage location where Maven stores libraries (dependencies)
and plugins. There are three types of repositories:
○ Local Repository: Stored on your local machine.
○ Central Repository: The default repository that contains thousands of public
dependencies.
○ Remote Repository: Custom or private repositories that teams can use to host
dependencies.
61. Explain Maven lifecycle phases.
● Maven’s build lifecycle consists of several phases, and each phase performs a specific
task in the build process:
○ validate: Validates the project setup.
○ compile: Compiles the source code.
○ test: Runs tests on the compiled code.
○ package: Packages the compiled code into a JAR/WAR file.
○ install: Installs the packaged code to the local repository.
○ deploy: Deploys the project to a remote repository for sharing.
62. What is the purpose of the Maven clean phase?
● clean phase: This phase deletes the target/ directory, which contains the output of
previous builds. It ensures that subsequent builds start with a clean slate and avoids
using outdated files from previous builds.
63. What is the purpose of the Maven install phase?
● The install phase installs the built artifact (JAR, WAR, etc.) into your local Maven
repository. This allows other projects on your machine to access this artifact as a
dependency.
64. What's the difference between Java 8's Optional and traditional null
checks?
● Optional is a container object which may or may not contain a non-null value. It
provides a more functional way of handling null values, eliminating the need for
traditional null checks (if (object == null)).
● Traditional Null Checks: Often involve writing verbose conditional statements to check if
an object is null and handle it accordingly.
● Advantages of Optional: Improves readability, reduces boilerplate code, and helps in
better handling of null by using methods like .orElse(), .ifPresent(), etc.
65. Explain the purpose of functional interfaces in Java.
● Functional interfaces are interfaces that have exactly one abstract method and can
therefore be used as the target for lambda expressions and method references.
● They enable the functional programming paradigm in Java, making code more concise
and expressive.
66. What is the difference between Stream.forEach() and
Collection.forEach()?
● Stream.forEach(): Executes a given action for each element in the stream. It is
generally used for processing a stream in a functional style and is part of the Stream
API.
● Collection.forEach(): Executes a given action for each element in the collection
(like a list or set). It is part of the Iterable interface.
○ Key Difference: Stream.forEach() is designed for use with streams (supports
parallelism and functional operations), while Collection.forEach() works
directly with collections.
67. How does the CompletableFuture class improve async
programming?
● CompletableFuture allows you to write asynchronous, non-blocking code in a cleaner
and more flexible way.
○ You can chain multiple asynchronous tasks, handle exceptions, and apply
various transformations or combinations of futures.
○ It improves code readability, avoids callback hell, and allows parallel execution
with better handling of results.
68. What are default and static methods in interfaces?
● Default Methods: Methods in an interface with a body, introduced in Java 8. They allow
interfaces to have implementations while maintaining backward compatibility.
○ Example: default void method() { ... }
● Static Methods: Methods that belong to the interface itself, not to instances of the
interface. Static methods can be called on the interface, not on its implementations.
○ Example: static void staticMethod() { ... }
69. How does the var keyword work in Java 10?
● The var keyword is a local variable type inference feature introduced in Java 10. It
allows the compiler to infer the type of a local variable based on the assigned value.
○ Example: var number = 10; (Java will infer number as int).
70. What are records in Java, and how do they simplify data classes?
● Records are a new feature introduced in Java 14 as a preview and made stable in Java
16. They provide a concise way to create immutable data classes.
○ Records automatically generate equals(), hashCode(), and toString()
methods.
○ Example: public record Person(String name, int age) {} simplifies
boilerplate code for data objects.
71. What is the sealed keyword in Java, and how does it enhance
inheritance?
● sealed classes restrict which other classes or interfaces can extend or implement them.
○ It enhances inheritance by allowing the class author to control and limit the types
that can subclass or implement the class, improving type safety.
○ Example: sealed class Shape permits Circle, Rectangle {} allows
only Circle and Rectangle to extend Shape.
72. How does the pattern matching feature improve instanceof checks?
● Pattern matching simplifies and improves the readability of instanceof checks by
eliminating the need for casting.
Example: Before:
if (obj instanceof String) {
String str = (String) obj;
// use str
After pattern matching:
if (obj instanceof String str) {
// use str directly
73. What are the improvements in garbage collection in Java 11+?
● Java 11 and later versions introduced several improvements to garbage collection:
1. ZGC (Z Garbage Collector): Low-latency garbage collector aimed at large heap
sizes (from GB to TB). It minimizes pauses.
2. Shenandoah GC: A low-pause-time garbage collector, introduced in Java 12,
also aimed at large heaps.
3. Garbage Collector Improvements: Improved performance in terms of latency,
throughput, and heap management.
4. Epsilon GC: A no-op garbage collector introduced in Java 11 that does not
perform any garbage collection, useful for benchmarking or testing.