0% found this document useful (0 votes)
41 views34 pages

Short Java 8 Notes

The document discusses the use of Comparable and Comparator interfaces in Java for sorting objects, highlighting their differences and usage scenarios. It also covers various data structures like HashMap, ArrayList, LinkedList, and ConcurrentHashMap, explaining their real-world applications and advantages. Additionally, it addresses multithreading concepts, including ExecutorService, and provides examples of handling concurrent tasks in web servers, e-commerce, banking, and gaming.

Uploaded by

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

Short Java 8 Notes

The document discusses the use of Comparable and Comparator interfaces in Java for sorting objects, highlighting their differences and usage scenarios. It also covers various data structures like HashMap, ArrayList, LinkedList, and ConcurrentHashMap, explaining their real-world applications and advantages. Additionally, it addresses multithreading concepts, including ExecutorService, and provides examples of handling concurrent tasks in web servers, e-commerce, banking, and gaming.

Uploaded by

xepif75442
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

1. Comparable ([Link].

Comparable) class NameComparator implements


Comparator<Student> {
●​ Purpose: Defines the natural ordering of
objects. public int compare(Student s1,
●​ Method to implement: compareTo(T o) Student s2) {
●​ Used when: You want the object itself to be return
comparable (self-comparison logic). [Link]([Link]); // sort by
●​ Modifies the class: Yes, you need to modify name
the class and implement the interface.​ }
}

Example:
public class Student implements Usage:
Comparable<Student> {
[Link](list, new
int rollNo;
NameComparator());
String name;

public Student(int rollNo, String


🔸 Java 8+: Lambda with Comparator
name) { [Link]((s1, s2) ->
[Link] = rollNo; [Link]([Link]));

}
[Link] = name;
✅ Key Differences:
Feature Comparable Comparator
@Override
public int compareTo(Student other) Packag [Link] [Link]
{ e
return [Link] -
[Link]; // sort by rollNo Method compareTo(Ob compare(Object
ascending ject o) o1, Object o2)
}
Used for Natural ordering Custom ordering
}

Modifies Yes (implements No (separate class


class? inside the class) or lambda)
Usage:
List<Student> list = new ArrayList<>(); Multiple No (one Yes (can have
[Link](list); // Uses sorting? implementation multiple)
compareTo() only)

🔹 2. Comparator ([Link]) Exampl


e
Collections.
sort(list)
[Link]
rt(list,
comparator)
●​ Purpose: Defines custom sorting logic,
outside the object class.
●​ Method to implement: compare(T o1, T
o2) Perfect! Let’s take a real-world scenario often asked
●​ Used when: You want to sort objects in in Java interviews, especially for experienced roles:
multiple different ways.
●​ Modifies the class: No, it keeps the class
unchanged.
🔹 Scenario: Sorting Employees
Example: You have an Employee class with fields:
public class Employee { return
int id; [Link]([Link]);
String name; }
double salary; }
// constructor, getters/setters // Sort by salary (descending)
} class SalaryComparator implements
Comparator<Employee> {
Now, the requirement is: public int compare(Employee e1,
Employee e2) {
1.​ Sort employees by id (natural order).
return [Link]([Link],
2.​ Sometimes, sort by name (alphabetically).
[Link]); // note: reversed order
3.​ Sometimes, sort by salary (descending
}
order).
}

✅ Solution using Comparable and 💻 Usage


Comparator
List<Employee> employees = new

1. ✅ Use Comparable for natural ordering (by id) ArrayList<>();


[Link](new Employee(101, "Alice",
public class Employee implements
50000));
Comparable<Employee> {
[Link](new Employee(103, "Bob",
int id;
60000));
String name;
[Link](new Employee(102,
double salary;
"Charlie", 55000));

public Employee(int id, String name,


// Sort by natural order (id)
double salary) {
[Link](employees);
[Link] = id;
[Link] = name;
// Sort by name
[Link] = salary;
[Link](employees, new
}
NameComparator());
// Sort by salary descending
@Override
[Link](employees, new
public int compareTo(Employee other)
SalaryComparator());
{
return [Link] - [Link]; //
natural sort by id
💡 Java 8+ Lambda Version (Cleaner)
} // Sort by name
} [Link]((e1, e2) ->
[Link]([Link]));
2. ✅ Use Comparator for custom sorting
// Sort by name // Sort by salary descending
class NameComparator implements [Link]((e1, e2) ->
Comparator<Employee> { [Link]([Link], [Link]));
public int compare(Employee e1,
Employee e2) {
Real World Examples: ​
ConcurrentHashMap<String, Double> stockPrices = new

ConcurrentHashMap<>();
1. HashMap (Key-Value Storage) [Link]("AAPL", 150.0); // Thread-safe
[Link]("AAPL", (k, v) -> v *
Use Case: Caching User Sessions in a Web Application
1.02); // Atomic update
●​ Stores user session data (e.g., sessionId → Why ConcurrentHashMap?
User object). ●​ Thread-safe without locking the entire map.
●​ Fast O(1) lookups for login/logout ●​ Higher throughput than
operations.
Hashtable/[Link]().
Map<String, User> sessionCache = new HashMap<>();
[Link]("SESS123", new User("Alice")); Summary Table
User currentUser = [Link]("SESS123"); //
Retrieve user Collection Real-World Use Key Advantage
Why HashMap? Case
●​ No duplicate keys (unique session IDs).
●​ Unsynchronized (faster for single-threaded
HashMap User session Fast O(1)
apps).
caching lookups
2. ArrayList (Dynamic Array)
Use Case: E-Commerce Shopping Cart ArrayList Shopping cart Fast random
●​ Stores items added by a user (order matters, items access
allows duplicates).
●​ Fast random access (e.g., "Show item at
LinkedList Music playlist Efficient
index 3").
insertions/deleti
List<Product> cart = new ArrayList<>(); ons
[Link](new Product("Phone"));
[Link](new Product("Case"));
Product firstItem = [Link](0); // O(1) access Array Chessboard grid Fixed-size,
Why ArrayList? memory-efficien
●​ Iteration-friendly. t
●​ Slower for frequent insertions/deletions in the
middle.
ConcurrentH Real-time stock Thread-safe,
ashMap price updates high
3. LinkedList (Doubly-Linked List)
Use Case: Music Playlist (Next/Previous Navigation) concurrency
●​ Efficient insertions/deletions (e.g.,
adding/removing songs). When to Use Which?
●​ Sequential access (ideal for queues/stacks).
●​ Need key-value pairs? → HashMap (or
LinkedList<String> playlist = new LinkedList<>(); ConcurrentHashMap for threads).
[Link]("Song1");
[Link]("Song2");
●​ Frequent iteration/random access? →
[Link](); // Efficient for FIFO ArrayList.
Why LinkedList? ●​ Frequent insertions/deletions? →
●​ O(1) for head/tail operations. LinkedList.
●​ Poor random access (get(index) is O(n)). ●​ Fixed-size data? → Array.
4. Array (Fixed-Size) ●​ High-concurrency key-value? →
ConcurrentHashMap
Use Case: Chessboard (8x8 Grid)
●​ Fixed-size, memory-efficient for known
dimensions. Fail-Fast vs. Fail-Safe Iterators in
Piece[][] chessboard = new Piece[8][8]; Java
chessboard[0][0] = new Piece("Rook"); 1. Fail-Fast Iterators
Why Array?
●​ Lowest overhead.
Definition:​
●​ Size cannot change after creation. Fail-fast iterators immediately throw a
ConcurrentModificationException if the
5. ConcurrentHashMap (Thread-Safe Maps) collection is modified while iterating (except
Use Case: Stock Price Updates in a Trading App
●​ Handles concurrent updates (e.g., multiple via the iterator's own methods like
threads updating stock prices). remove()).
How it Works: [Link]("D"); // No exception, but
iterator won't see "D"
●​ Uses an internal modification
}
counter (modCount).
Use Cases:
●​ On each operation (add/remove), ●​ Multi-threaded environments
modCount increments.
(thread-safe).
●​ During iteration, it checks if ●​ When modification during iteration is
modCount has changed unexpectedly.
expected.
Examples:
●​ ArrayList, HashMap, HashSet Key Differences
(iterators from Collections
framework).​ Feat Fail-Fast Fail-Safe
ure
Code Example:
List<String> list = new Exce Throws No exception
ArrayList<>([Link]("A", "B", "C")); ption ConcurrentMod
Iterator<String> it = [Link](); ificationExce
while ([Link]()) { ption
String item = [Link]();
[Link]("D"); // Throws
ConcurrentModificationException Unde Operates on Operates on a
} rlying original clone/snapshot
Use Cases: Data collection
●​ Debugging unintended modifications.
●​ Single-threaded environments (not Perfo Faster (no Slower (due to
thread-safe). rman cloning copying)
ce overhead)
2. Fail-Safe Iterators
Definition:​
Fail-safe iterators do not throw exceptions if Thre Not Thread-safe
the collection is modified during iteration. ad thread-safe
Instead, they work on a clone or snapshot of Safet
the original collection. y
How it Works:
●​ Operates on a copy of the data (e.g., Exa ArrayList, ConcurrentHash
ConcurrentHashMap uses a mple HashMap Map,
s CopyOnWriteArr
snapshot).
ayList
●​ Changes to the original collection
after iteration starts are not reflected
in the iterator. When to Use Which?
Examples: ●​ Fail-Fast:
●​ ConcurrentHashMap, ○​ Single-threaded apps.
CopyOnWriteArrayList, ○​ Early detection of bugs
CopyOnWriteArraySet. (unexpected modifications).
Code Example: ●​ Fail-Safe:
○​ Concurrent modifications
List<String> list = new (multi-threading).
CopyOnWriteArrayList<>([Link]("A",
○​ Tolerate changes during
"B", "C"));
Iterator<String> it = [Link](); iteration.
while ([Link]()) { Java 8+ Tip: Use ConcurrentHashMap for
String item = [Link](); thread-safe maps or
[Link]() for ●​ Race conditions can occur if two
immutable views​ users buy the last item
simultaneously.
Real-World Multithreading Scenarios in Solution:
Java​ ●​ Use synchronized blocks or
ReentrantLock for thread-safe
Multithreading is essential for improving inventory updates.
performance, responsiveness, and efficiency ●​ Example:
in applications. Below are practical
private final Lock lock = new
scenarios where multithreading is commonly ReentrantLock();
used:
public void placeOrder(Product product) {
[Link]();
1. Web Servers (Handling Multiple try {
Requests) if ([Link]()) {
Scenario: [Link]();
●​ A web server (e.g., Tomcat, Jetty) [Link]("Order
placed!");
must handle thousands of
}
simultaneous HTTP requests. } finally {
●​ Each request is processed in a [Link]();
separate thread to avoid blocking }
others. }
How it Works: Why Multithreading?
●​ A Thread Pool (ExecutorService) ●​ Concurrent orders must be
manages worker threads. processed without overselling.
●​ Each thread processes a different
client request. 3. Banking (ATM Transactions)
Example: Scenario:
●​ Multiple ATMs withdraw/deposit
ExecutorService threadPool =
[Link](100); // 100
money from the same bank account.
threads ●​ Data corruption can happen if two
for (HttpRequest request : ATMs modify balance at the same
incomingRequests) { time.
[Link](() -> Solution:
processRequest(request));
}
●​ Use synchronized methods or
Why Multithreading? AtomicInteger for thread-safe
●​ Scalability: Handles multiple users balance updates.
without slowing down. ●​ Example:
class BankAccount {
●​ Responsiveness: One slow request private int balance = 1000;
doesn’t block others.
public synchronized void withdraw(int

2. E-Commerce (Inventory & amount) {


if (balance >= amount) {
Order Processing) balance -= amount;
}
Scenario: }
●​ An online store must handle multiple }.
orders while updating inventory in
real-time.
4. Gaming (Real-Time Stock Process live BlockingQueu
Multiplayer) Market data without e

Scenario: Feeds delay


●​ A multiplayer game (e.g., PUBG,
Fortnite) must update player Video Speed up ForkJoinPool
positions in real-time. Renderi frame
●​ Each player’s movement runs in a ng processing
separate thread.
Solution: Chat Send & receive Two threads
●​ Use thread-safe collections Apps messages in (Producer-Co
(ConcurrentHashMap) for player data. parallel nsumer)
●​ Example:

ConcurrentHashMap<String, PlayerPosition>
livePlayers = new ConcurrentHashMap<>();
✅ Use
Key Takeaways
multithreading for:
●​ Performance (parallel processing).
●​ Responsiveness (UI remains
// Thread 1: Updates player position
[Link]("Player1", new Position(x,
smooth).
y)); ●​ Scalability (handling multiple
clients).​
// Thread 2: Reads positions for rendering
PlayerPosition pos =
[Link]("Player1");
Why Multithreading?
🔷 What is ExecutorService?
ExecutorService is part of the
●​ Real-time synchronization of game [Link] package and provides a
state. high-level API to manage threads.​

Scenari Problem Java Tools


✅ Instead of creating threads manually:
java
o Solved Used
CopyEdit
Thread t = new Thread(() ->
Web Handle ExecutorServ
doSomething());
Servers multiple ice, Thread
requests Pools [Link]();

We use:
E-Com Prevent synchronized,
ExecutorService executor =
merce overselling ReentrantLoc
inventory k [Link](5);
[Link](() ->
doSomething());

🏪
Banking Avoid AtomicIntege
(ATM) incorrect r,
balance synchronized Real-world Analogy: A
updates
Restaurant and Chefs
Imagine a restaurant (your application) that
Multipla Sync player ConcurrentHa
handles food orders (tasks). You have:
yer positions in shMap
●​ Waiters taking orders (main thread /
Games real-time
client requests)​
●​ A pool of chefs (threads) who cook ExecutorService executor
the meals =
●​ A kitchen manager (ExecutorService) [Link](3);
who assigns orders to chefs​
Runnable balanceTask = ()
Benefits:
-> {
●​ Chefs (threads) are reused
●​ No need to hire (create) and fire
(destroy) for every new order [Link]("Checking
●​ Smooth operation with better balance: " +
performance and scalability [Link]().getName())

🔧 Basic Syntax:
ExecutorService executor =
;
try {
[Link](2000); } catch
[Link](3); (InterruptedException e) {}

[Link](() -> { [Link]("Balance


// Your task logic here fetched.");
}); };

[Link](); // always Runnable transferTask =


shut down after tasks () -> {

💻 Real-world Example:
Processing Customer Bank
[Link]("Transferring
money: " +
[Link]().getName())
Requests​ ;
try {
[Link](3000); } catch
Suppose you’re building a banking backend
system that processes various customer (InterruptedException e) {}
tasks like:
●​ Balance inquiry [Link]("Money
●​ Money transfer transferred.");
●​ Bill payment​ };

Each of these is a time-consuming Runnable billPaymentTask


operation, and you want to run them = () -> {
asynchronously.​

👇 Code Example:
import [Link].*;
[Link]("Paying bill:
" +
[Link]().getName())
public class BankRequestProcessor
;
{
try {
[Link](1000); } catch
public static void
(InterruptedException e) {}
main(String[] args) {
management. It improves
[Link]("Bill paid."); scalability and avoids the
}; overhead of manually creating
[Link](balanceTask);​ and managing threads.”​
[Link](transferTask);
[Link](billPaymentTask); In an Airlines Reservation System


[Link](); //
Don't forget this!
} Common Microservices in
} an Airline Project
🔍 Important Types of
Executors:
Here’s a detailed breakdown of the most
common microservices you’d design:

1. User Service / Account Service


Executor Type Description Handles user registration, login,
authentication, profile updates, etc.
newFixedThr Fixed number of Responsibilities:
eadPool(n) threads. ●​ Signup, login, password reset
●​ JWT token generation
newCachedTh Dynamic threads, grows ●​ Profile management​

🧱 Tech: Spring Security, OAuth2/JWT


readPool() as needed.

newSingleTh Single-threaded, tasks


readExecuto execute one by one. 2. Search Service
r() Allows customers to search for flights.
Responsibilities:
newSchedule For scheduled tasks ●​ Search flights by source, destination,
dThreadPool (like cron jobs). date
(n) ●​ Filter results (by time, airline, price)

✅ Best Practices:
●​ Return available seats, prices​

●​ Always shut down the executor


🔍 Might call Flight Inventory Service to
check real-time availability.
(shutdown() or shutdownNow()).​
3. Flight Inventory Service
●​ Handle exceptions using try/catch Manages flights, seat map, schedules,
or [Link]() if submitting aircraft details.
Callable.​ Responsibilities:
●​ Add/update/delete flight info
●​ Real-time seat availability
●​ Use Callable<T> when you need a
●​ Manage aircraft and route info​
return value.​

🧠 Interview Tip:
4. Booking Service
Handles ticket booking and cancellation.
Responsibilities:
“ExecutorService decouples ●​ Book flights
task submission from thread
●​ Confirm seat availability (via Flight
Inventory) 9. Admin Service
●​ Generate booking reference number Internal service for staff to manage flights,
(PNR) pricing, maintenance, etc.
●​ Cancel reservations​ Responsibilities:

🎫 Critical for concurrency: Prevent double


bookings.
●​ Flight schedule updates​

●​ Fare class changes​

5. Payment Service ●​ Staff login and dashboards


Handles all payment-related operations.
Responsibilities:
●​ Initiate payment
🔐 1. Secure APIs using
Spring Security + JWT​
●​ Integrate with payment gateways

✅ Why?
(Razorpay, Stripe, etc.)
●​ Refunds
●​ Transaction logs​ You want to ensure that only authenticated

💳 Can be secured with PCI DSS


services/users (like Booking or Admin) can call
the Notification Service.
compliance and audit logs.
🔧 Basic Steps
Step 1: Add Dependencies in [Link]
6. Check-In Service xml
Handles passenger check-in and seat <dependency>
selection.
<groupId>[Link]</groupId>
Responsibilities:
●​ Online check-in <artifactId>spring-boot-starter-security</art
●​ Seat map UI ifactId>
●​ Baggage check-in integration </dependency>
<dependency>
<groupId>[Link]</groupId>
7. Notification Service <artifactId>jjwt</artifactId>
Sends notifications like email/SMS for <version>0.9.1</version>
booking, cancellations, delays, etc. </dependency>

Responsibilities:
●​ Send email, SMS, or push Step 2: Create JwtTokenFilter to validate
notifications incoming tokens
●​ Booking confirmation java
public class JwtTokenFilter extends
●​ Flight status updates​ OncePerRequestFilter {

📨 Often event-driven using


Kafka/RabbitMQ.
@Override
protected void
doFilterInternal(HttpServletRequest request,

8. Loyalty / Rewards Service HttpServletResponse response,


Manages frequent flyer points and rewards.
FilterChain filterChain)
Responsibilities: throws
●​ Track miles/points​ ServletException, IOException {
String authHeader =
●​ Apply points to bookings [Link]("Authorization");
if (authHeader != null &&
●​ Redeem rewards [Link]("Bearer ")) {
String jwt =
[Link](7); [Link]().setSigningKey(SECRET_KEY).parse
// validate token logic here ClaimsJws(token);
if ([Link](jwt)) { return true;
// Set user authentication in } catch (Exception e) {
the context return false;
}
UsernamePasswordAuthenticationToken auth = }
new }

🔒 2.
UsernamePasswordAuthenticationToken("service"
, null, new ArrayList<>());
Role-Based Access Control
[Link]().setAuthent
ication(auth); (RBAC)
} Add roles in JWT claims and verify them.
} java
CopyEdit
.antMatchers("/notify/internal/**").hasRole("
[Link](request,
INTERNAL_SERVICE")
response);

📢 3.
}
}
Service-to-Service
Step 3: Configure Spring Security
Communication Security
If other microservices (like Booking) call Notification
java
Service:
@Configuration Option A: Use JWT with a shared
@EnableWebSecurity secret between services
public class SecurityConfig extends
Generate tokens with ROLE_INTERNAL_SERVICE,
WebSecurityConfigurerAdapter {
and only trusted services can use them.
@Override Option B: Use mutual TLS (mTLS)
protected void configure(HttpSecurity Use client/server certificates to authenticate each

🕵️ 4. Audit Logging
http) throws Exception { service.
[Link]().disable()
.authorizeRequests()
Log:
.antMatchers("/notify/**").authenticated() ●​ Who sent the notification
.and() ●​ What data was sent
●​ When and to whom​

🛡️ 5.
.sessionManagement().sessionCreationPolicy(Se
[Link]);

[Link](new
Rate Limiting & Throttling
JwtTokenFilter(),
Use tools like:
[Link]);
●​ Spring Bucket4j
}
●​ API Gateway (e.g., Kong, NGINX, Spring
Cloud Gateway)​
}

🚨 6.
To prevent abuse (e.g., spamming SMS/Emails).
Step 4: Validate JWT Tokens
java Exception & Security Logging
public class JwtUtil { Log unauthorized attempts and unexpected
tokens with IP addresses.

🔁
private static final String SECRET_KEY =
"my-secret-key";

public static boolean


Bonus: Event-Driven with
validateToken(String token) { Security (Kafka)
try { If you're triggering notifications via Kafka:
●​ Secure Kafka with SSL and SASL
●​ Validate the message source with internal private final ExecutorService executor =

✅ Final Summary Table:


service headers or tokens​ [Link](10);

// Cron: run every 5 minutes


@Scheduled(cron = "0 */5 * * * *") //
Feature How to Implement every 5 min
public void validatePendingPnrs() throws
API Spring Security + JWT InterruptedException {
Authentication List<String> pendingPnrs =
fetchPnrsToValidate(); // from DB, etc.
Role-based Roles in JWT, checked via Spring
access Security List<Callable<ValidationResult>>
tasks = new ArrayList<>();
Service-to-servi JWT or mutual TLS for (String pnr : pendingPnrs) {
ce [Link](() -> {
boolean isValid =
Data validation Sanitize inputs to avoid script
callExternalService(pnr);
injection
return new
Rate limiting API Gateway / Bucket4j ValidationResult(pnr, isValid, false);
});
}
Auditing Store logs of every notification
triggered
List<Future<ValidationResult>>
Kafka events Secure with SSL, validate headers futures = [Link](tasks, 5,
[Link]);

for (int i = 0; i < [Link]();
Corn-Based MultiThread: ​

🧠 Real-World Architecture:
i++) {
Future<ValidationResult> f =
[Link](i);
1.​ Spring’s @Scheduled(cron = "...") is used String pnr = [Link](i);
to trigger the batch process, say, every 5
minutes.​ if ([Link]()) {
[Link](pnr + " —
2.​ Inside the scheduled method:​ Timed out");
} else {
○​ You fetch the list of pending/impacted
PNRs (e.g., for upcoming schedule try {
changes).​ ValidationResult result =
[Link]();
○​ You process them in parallel using [Link](pnr +
ExecutorService + Callable with " — Valid: " + [Link]);
timeout (as shown earlier).​ } catch (Exception e) {


[Link](pnr +
" — Failed: " + [Link]());
Example: Cron + }
}
Multi-threaded Callable }
java }
import
[Link] private List<String>
eduled; fetchPnrsToValidate() {
import // Normally you query DB for pending
[Link]; schedule changes
return [Link]("OK123", "FAIL456",
import [Link].*; "LATE789");
import [Link].*; }

@Service private boolean


public class ScheduleChangeValidator { callExternalService(String pnr) {
try {
processing
[Link](1000); // Simulate 🔹 Example:
} catch (InterruptedException http
ignored) {} GET /api/flights/DEL-MUM
return [Link]("OK");
}
The server might return: json
private record ValidationResult(String
pnr, boolean valid, boolean timeout) {} {
"flightNumber": "AI302",

🔧 Setup Required
}
"departure": "Delhi",
"arrival": "Mumbai",
"duration": "2h"
1.​ Add @EnableScheduling in your Spring Boot
main class:​ }

@SpringBootApplication
@EnableScheduling
public class AirlineApp {
🔧 Built with:
public static void main(String[] args) { In Spring Boot, you create a REST API using
@RestController and @RequestMapping.
[Link]([Link],
args);
} java
} @RestController
2.​ Tune thread pool size as needed @RequestMapping("/api/flights")


([Link](n)).​ public class FlightController {

Cron Expression Cheatsheet @GetMapping("/{route}")


Cron Meaning public Flight
getFlight(@PathVariable String route) {
"0 */5 * * * *" Every 5 minutes return
[Link](route);
"0 0 2 * * *" Every day at 2 AM }
}
"0 0/1 * * * *" Every 1 minute

"0 0 0 * * MON" Every Monday at midnight


✅ What it is:
WebClient is a non-blocking HTTP client
introduced in Spring WebFlux (replacement for
REST API VS WebClient
RestTemplate), used to call other REST APIs.

✅ What it is: 📌 Think of it as: “A client inside your


microservice that calls another REST API.”

🔹 Example:
A REST API (Representational State Transfer API)
is a web service endpoint that exposes data or
functionality over HTTP.

📌 Think of it as: “A server that provides


services/data over HTTP, typically in JSON format.”
If your Booking Service needs to fetch flight details
from the Flight Service, it uses WebClient.

java
WebClient client = [Link]();
Flight flight = [Link]()
.uri("[Link]
🔁 Real-World Microservices Use
Case
DEL-MUM")
.retrieve() 1. Flight Service exposes a REST
.bodyToMono([Link]) API:
.block(); // blocking call

✅ Summary of
http
GET /api/flights/DEL-MUM

Differences 2. Booking Service calls it via


Feature REST API WebClient (Client
WebClient:
(Server Side) Side) java
Flight flight = [Link]()
Purpose Exposes Consumes
.uri("[Link]
functionality functionality from
DEL-MUM")
via HTTP a REST API
endpoints .retrieve()
.bodyToMono([Link])
Role Provider Consumer (client) .block();
(server)

Typical Define API in Call API using


MAP() VS FLATMAP()
Use @RestControl [Link]
ler te() Aspe map() flatMap()
ct
Direction Receives HTTP Sends HTTP
requests requests Funct The function The function passed
ion passed returns returns a stream,
Technolo Spring Web Spring WebFlux Outp a single value optional, or another
gy MVC (WebClient) ut or wrapped wrapped type, which will
(@RestControl type per input. be flattened.
ler)
Mapp One-to-one One-to-many or
ing mapping. one-to-zero mapping.
Blocking Doesn’t matter Non-blocking
Type
/Non-blo (depends on (Reactive), but
cking app design) can block if
Oper Performs only Performs transformation
needed
ation transformation. + flattening.
Replaces — Replaces
? RestTemplate Outp Produces a Produces a flattened
ut Stream<T>, structure like
Struct Optional<T>, or Stream<T>, not

🧠 Interview Tip: ure

Use
Mono<T>.

Use when each


Stream<Stream<T>>.

Use when each input


"REST API is what you create to Case input maps to a maps to a
expose data; WebClient is what you single output. stream/collection/optiona
use to call other APIs — often inside l, and you want to flatten
microservices when services need to it.
communicate.
Exam
ple
Stream<Stri Stream<String> → Maintains ✅ Yes, preserves insertion
ng> → Stream<Character> Order? order
Stream<Inte
ger>
(by flattening
Stream<List<Charac Thread-saf ❌ No (use
ter>>) e? [Link]
Map() if needed)
MAP() EXAMPLE: ​
List<String> names = Allows ✅ One null key, multiple null
[Link]("alice", "bob", null values allowed
"charlie"); keys/value
List<String> upperNames = s?
[Link]()
Performan Slightly slower than HashMap
ce (due to overhead of
.map(String::toUpperCase) // "ALICE",
maintaining order)
"BOB", "CHARLIE"
.toList();​ Backed by Hash table + Doubly linked list

FLATMAP():
List<String> sentences =
🔁 Internal Structure:
[Link]("Hello World", "Java LinkedHashMap maintains a doubly-linked
Streams"); list of Entry<K, V> objects in the order they
List<String> words = were inserted.
[Link]()
Each entry has extra pointers:​
.flatMap(s -> [Link]([Link](" static class Entry<K,V> extends
"))) // "Hello", "World", "Java", [Link]<K,V> {
"Streams"
.toList(); Entry<K,V> before, after; //
​ pointers to maintain insertion order
Q) How does LinkedHashMap maintain }​
insertion order?​ ​
LinkedHashMap is a subclass of HashMap in When a new entry is added:
Java that:
●​ It’s stored in the hash table like in HashMap
●​ Maintains insertion order of elements for O(1) lookup.
●​ It’s also linked at the end of the doubly-linked
●​ Uses a doubly-linked list internally to
list.
preserve the order in which entries ●​ "LinkedHashMap maintains insertion order by
were added using a doubly-linked list that runs through its

✅ Key Properties of
entries."

LinkedHashMap
Q)What is the purpose of the Map
Feature Description interface?​
The Map interface represents a collection of
key-value pairs, providing methods for storing,
retrieving, and manipulating key-value associations.
🔹 2. Using LinkedHashSet
(Preserves Insertion Order)​
Map<String, String> capitalMap = new HashMap<>();​ List<String> list =
[Link]("India", "New Delhi");​ [Link]("apple", "banana",
[Link]("USA", "Washington DC");​
"apple", "orange");​
[Link]([Link]("India"));​
List<String> unique = new

Q) How does the contains() method work in ArrayList<>(new LinkedHashSet<>(list));​
a Set?​ [Link](unique); // [apple,
banana, orange]​
The contains() method checks if a specified
element exists in a Set by computing its hash ✅ Best of both worlds — removes duplicates and
preserves original order.

🔹 3. Using Java 8+ Streams​
code and looking for it in the appropriate bucket.

Q)What happens when you insert a null a. Remove duplicates and collect to list:​
key into a HashMap? ​ List<String> unique = [Link]()​
When you insert a null key into a HashMap, it .distinct().collect([Link]())
allows one null key, while Hashtable does not permit
;
null keys or values​

Q) What is the difference between
Q) How do you convert an ArrayList to
[Link]() and [Link]()?
an array?​
You can convert an ArrayList to an array using the
●​ [Link]() is a static
toArray () method, which can be called with or
without an array parameter.​ method used to sort any list
​ passed to it.
Q)What are the different ways to ●​ [Link]() is a default method
added in Java 8 to the List
traverse a List?​
interface and sorts the list
You can traverse a List using a for loop,
in-place using a comparator.
enhanced for loop, Iterator, or ListIterator. ​

Q) How do you remove duplicates Q) How can you synchronize a List in
Java?

🔹 1. Using Set (Most Common)


from a List?​
●​ Use
[Link](new
Since a Set in Java doesn’t allow duplicates, it's ArrayList<>()) for thread-safe
the easiest way.​ list.
List<String> list =
●​ Or use CopyOnWriteArrayList for
[Link]("apple", "banana",
better performance in read-heavy
"apple", "orange");​
concurrent scenarios.
List<String> unique = new
ArrayList<>(new HashSet<>(list));​
Q) What is the difference between
[Link](unique); // [orange,
subList() and slice()?
banana, apple] — order not guaranteed​
⚠️ Note: Order may not be preserved.
●​ subList(from, to) returns a view
of the list (not a new list).
Changes affect the original list.​
●​ slice() is not a Java method — it ●​ clone() creates a shallow copy
comes from other languages like (must cast result).
Python. ●​ copyOf() (Java 10+) creates a new
immutable copy of the collection.
Q) Explain the poll() and remove()
methods in the Queue interface. Q) How do you sort a Set using a
custom comparator?
●​ poll() removes and returns the
head; returns null if empty. ●​ Convert it to a List, sort with a
●​ remove() removes and returns the comparator:​
head; throws exception if empty. List<String> list = new
ArrayList<>(set);​
Q) What is the significance of the [Link](customComparator);
retainAll() method?
Q) How can you check if two
●​ It modifies the collection to collections are equal?
retain only elements that are also
present in another collection — ●​ Use equals() method.
useful for finding intersection. ●​ It checks:​

Q) What is a WeakHashMap, and when ○​ Same size


would you use it? ○​ Same elements (order
matters for List, not for
●​ It stores keys as weak references. Set)
If a key is no longer referenced
elsewhere, it's eligible for GC. Q) Explain the concept of a
●​ Useful in memory-sensitive caches. [Link] in a HashMap.

Q) How do you implement a stack ●​ Represents a key-value pair.


using the Collections Framework? ●​ Used when iterating through a map:​
for ([Link]<K, V> e :
●​ Use Deque like ArrayDeque:​ [Link]()) {// use
Deque<Integer> stack = new [Link](), [Link]()​
ArrayDeque<>();​ }
[Link](10); [Link]();
Q) What is the difference between
Q) What is a LinkedHashSet, and how remove() and clear() in collections?
does it differ from HashSet?
●​ remove(element) removes a specific
●​ LinkedHashSet maintains insertion item.
order using a doubly linked list. ●​ clear() removes all elements from
●​ HashSet does not maintain any the collection.
order.
Q) How can you find the intersection
Q) What is the difference between of two Sets?
clone() and copyOf() in collections?
●​ Use retainAll():
[Link](set2); // modifies set1 ●​ TreeSet keeps elements sorted.
●​ Supports range queries like
Q) How can you iterate over a Map in headSet(), tailSet().
Java? ●​ Slower than HashSet, but useful
when order matters.
for ([Link]<K, V> entry :
[Link]()) {}​ Q)Though, we are not adding any
for (K key : [Link]()) {}​ starters to Spring boot project,
[Link]((k, v) -> {}); Howdoes it gets multiple jar files
as the maven/gradle dependencies to
Q) What is the purpose of the the Project?
Collections utility class?
➔In every Spring boot Project, One
●​ Provides static helper methods:​ parent spring boot project will be
imported from the maven central repo
○​ Sorting (sort()) using<parent>tag.
○​ Searching (binarySearch())
○​ Creating synchronized, ➔Based on the parent spring boot
unmodifiable collections. project’s version, lots of things will
come to our spring boot project which is
Q) What is a SortedMap? nothing but a child project.

●​ A Map that maintains keys in a)Basic spring,spring boot jar files and
ascending order. dependent, relavent jar files.​
●​ Typically implemented using b)required plugins​
TreeMap. c)required Project Properties.

Q) Explain the difference between Q)How many ways are there to activate
toArray() and toArray(T[]). profiles in spring boot app?

●​ toArray() returns an Object[]. ➔There are multiple ways to use...but mainly 2


●​ toArray(T[] a) returns an array of approaches can be
the specified type:​ considered.
String[] arr = [Link](new i)using [Link]/yml(Best)
ii)using System property(-[Link]=dev)​
String[0]);

Q) How do you create an immutable Q)How can we configure custom
list in Java? properties file in spring/spring boot
Application?
➔In Spring Apps using @PropertySource Annotation,
List<String> list = [Link]("a", "b");
In Spring boot Apps using @PropertySource
// Java 9+​
annotation or using [Link] key of
List<String> readOnly = the [Link] file or spring:
[Link](original); config:
import: key of the [Link] file
Q) What are the advantages of using
a TreeSet over a HashSet?
Q)Can we use @ConfigurationProperties ➔-In “[Link] file”, We typically
and @Value annotation in single bean provide configuration settings for various aspect
class? of the Spring Boot application.
➔Yes, can be done ,Infact few values to spring -for example database settings, Server port
bean properties can be injected using @Value configuration, logging levels,and other
and the values to few other properties using application-specific properties.
@ConfigurationProperties annotation(Only in
spring boot apps).​ ➔i)@Configuration:-This annotation in Spring
​ indicates that the class can
Q)Define @ConfigurationProperties? be used to define bean configuration within the
Spring application context.​
➔-It’s a way to read values from your
➔-Dependent JAR:-A JAR file that your
[Link] or [Link] file and
application must have to run or compile — like
put them into a Java class automatically.
Spring libraries if you're using Spring Boot.
- So you don’t have to write @Value again and
again for every property.
Q)Which are the most important Spring Boot
You just create one class, and Spring fills in all
Starters?
the values for you.
➔i)Spring-boot-starter:-It is the core starter that
includes auto-configuration support, logging, and
Q))What is the difference between
YAML processing.
getForEntity() and getForObject() methods?
ii)Spring-boot-starter-web:-It provides
➔-getForEntity() return type is
dependencies to build web applications, including
ResponseEntity<T> which contains
Spring MVC, Restful Services, and embedded
response body(output),headers,status code and
Tomcat.
etc. -getForObject() return type is Object which
iii)Spring-boot-starter-data-jpa:-It provide
gives only response body(output)i.e It does not
dependencies for Spring Data JPA, Hibernate
give response headers,status code and etc.
and database connection pool.
iv)Spring-boot-starter-security:-It includes Spring
Q)What is Serializable interface?
Security and it’s dependencies for securing
➔In Java, Serializable is a marker interface used
application.
to tell the program. -"Hey, this object can be
v)Spring-boot-starter-thymeleaf:-It integrates the
saved, sent, or converted into a format (bytes)
Thymeleaf templating engine with Spring MVC.
that can be restored later."
vi)Spring-boot-starter-test:-It includes testing
libraries like Junit, Hamcrest and Mockito.
Q)What is lombok?
vii)Spring-boot-starter-actuator:-It provides
➔Lombok is a Java tool that helps you write less
production-ready features to help monitor and
code. It automatically adds things like getters,
manage your application
setters, constructors, and more, so you don't
viii)Spring-boot-starter-aop:-It brings in support
have to write them yourself.
for aspect-oriented programming using Spring
➔@Data is a shortcut from Lombok that saves
AOP and Aspect J.​
you from writing a lot of boring code in Java

classes.
Embedded Servers:- Spring Boot comes with
-When you use @Data it automatically creates
a built-in (embedded) web server, so you don't
Getters,Setters,toString(), equals() and
need to install or configure a separate server like
constructor.
Tomcat or Jetty — it runs right inside your
application.
Q)Define “[Link] file” in
Spring Boot Project?
Q)Where is the use of Spring Boot?
➔i)Web Application ii. Using Spring Initializr:​
ii)RESTful Web Services You can generate a Spring Boot project using Spring
iii)Microservices Initializr. It’s a web-based tool where you:
iv)Batch Processing
v)Integration with Other Technologies ●​ Choose your build tool (Maven or Gradle)
vi)Testing ●​ Select project metadata (Group, Artifact, Java
vii)Monitoring and Management​ version)
​ ●​ Add dependencies (e.g., Spring Web, JPA,
Security)
Q) What is @RestController in Spring ●​ Download a ready-to-run zip project.
Boot?
iii. Using Spring Boot CLI (Command-Line Interface):​
Answer: @RestController is used to You can use Groovy scripts and the Spring Boot CLI tool to
define RESTful APIs. It combines quickly prototype applications:
@Controller and @ResponseBody,
@RestController
meaning it returns data (JSON, XML)
class HelloController {
instead of views.
@RequestMapping("/")
Example:​ String home() {
@RestController "Hello Spring Boot CLI"
@RequestMapping("/api")
}
public class MyController {
}​
@GetMapping("/greet")
Run it using:
public String greet() { bash
return "Hello, World!";
spring run [Link]​
}

}
iv. Using Maven or Gradle manually:​
If you prefer manual setup:
Q) How to create a Spring Boot application?
●​ Maven: Use
There are several ways to create a Spring Boot application spring-boot-starter-parent and
depending on your preferences and tools: include spring-boot-maven-plugin in
your [Link].
i. Using @SpringBootApplication:​
The most common approach is to create a Java class <parent>
annotated with @SpringBootApplication and run <groupId>[Link]</group
the application using [Link](). Id>
<artifactId>spring-boot-starter-parent</
@SpringBootApplication
artifactId>
public class MyApplication {
<version>3.1.0</version>
public static void main(String[]
</parent>
args) {
<dependencies>
[Link]([Link]
<dependency>
s, args);
<groupId>[Link]</group
}
Id>
}
<artifactId>spring-boot-starter-web</art
ifactId>
</dependency>
</dependencies>
Q) How to create a simple RESTful API using Q) How to connect Spring Boot with a
Spring Boot?​ database?​
Answer: Create a class annotated with Answer: Use
@RestController and define handler methods spring-boot-starter-data-jpa
using annotations like @GetMapping, dependency and configure the datasource in
@PostMapping, etc.​ [Link].​

Example: Maven dependency:​


Xml​
@RestController <dependency>​
public class UserController { <groupId>[Link]</group
@GetMapping("/users") Id>​
public List<User> getAllUsers() { <artifactId>spring-boot-starter-data-jpa
return </artifactId>​
[Link](); </dependency>
}
} Q) How can you configure and use multiple
databases in a Spring Boot application?​
Answer: Follow these steps:
Q) What is the use of @RequestBody and
@ResponseBody annotations?​ 1️⃣ Configuration in
Answer: [Link]:
properties
●​ @RequestBody: Binds the HTTP # Primary DB
request body to a method parameter. [Link]=jdbc:m
●​ @ResponseBody: Indicates the return ysql://localhost:3306/db1
value of a method should be written [Link]=r
directly to the HTTP response body oot
(automatically handled in [Link]=r
@RestController).​ oot
[Link]-cla
ss-name=[Link]
Q) How do you handle query parameters in [Link]
Spring Boot?​ [Link]-auto=update
Answer: Use @RequestParam to bind URL
query parameters to method arguments.​ # Secondary DB
[Link]=jdbc
Example:​
:mysql://localhost:3306/db2
@GetMapping("/users")​
public List<User> [Link]
getUsers(@RequestParam("name") String =root
name) { [Link]
=root
return
[Link](name); }
[Link]-c
lass-name=[Link] .persistenceUnit("primary")
[Link] .build();
[Link]-auto=update }

@Bean(name =
2️ Create DataSource Configuration Class:
"secondaryEntityManagerFactory")
java public
@Configuration LocalContainerEntityManagerFactoryBean
@EnableTransactionManagement secondaryEntityManagerFactory(
public class DataSourceConfig { EntityManagerFactoryBuilder
builder,
@Primary
@Bean(name = "primaryDataSource") @Qualifier("secondaryDataSource")
@ConfigurationProperties(prefix = DataSource dataSource) {
"[Link]") return builder
public DataSource .dataSource(dataSource)
primaryDataSource() {
return .packages("[Link]")
[Link]().build();
} .persistenceUnit("secondary")
.build();
@Bean(name = "secondaryDataSource") }
@ConfigurationProperties(prefix =
"[Link]") @Primary
public DataSource @Bean(name =
secondaryDataSource() { "primaryTransactionManager")
return public PlatformTransactionManager
[Link]().build(); primaryTransactionManager(
}​ aryEntityManagerFactory")
@Qualifier("primEntityManagerFactory
@Primary emf) {
@Bean(name = return new
"primaryEntityManagerFactory") JpaTransactionManager(emf);
public }
LocalContainerEntityManagerFactoryBean
primaryEntityManagerFactory( @Bean(name =
"secondaryTransactionManager")
EntityManagerFactoryBuilder builder,
public PlatformTransactionManager
@Qualifier("primaryDataSource")
secondaryTransactionManager(
DataSource dataSource) {
return builder
@Qualifier("secondaryEntityManagerFactor
.dataSource(dataSource) y") EntityManagerFactory emf) {
.packages("[Link].p return new
JpaTransactionManager(emf);
rimary") } }
​ ○​ OAuth2, and more​
3️⃣ Define Repositories for Each DB:
●​ Implementation:
Primary DB Config: ○​ Via annotations like
@EnableWebSecurity and
java SecurityFilterChain (modern
@Configuration approach)
@EnableJpaRepositories( ○​ Can also include custom filters and
authentication providers.
basePackages =
"[Link]",
entityManagerFactoryRef = 2️⃣ Basic Authentication
"primaryEntityManagerFactory",
●​ What it is: A simple method where the client
transactionManagerRef = sends a username:password
"primaryTransactionManager" Base64-encoded in every HTTP request
) header.
public class PrimaryDatabaseConfig {}​ ●​ Use case: Suitable for internal services or
development environments.
●​ Spring Boot Support:
Secondary DB Config: ○​ Can be enabled using
java [Link]() in the security
@Configuration config.
@EnableJpaRepositories( ○​ Or just use default security starter
(generates default credentials).
basePackages =
"[Link]",
entityManagerFactoryRef = 3️⃣ JWT (JSON Web Token)
"secondaryEntityManagerFactory", Authentication
transactionManagerRef =
"secondaryTransactionManager" ●​ What it is: Token-based stateless
authentication.
)
●​ How it works:
public class SecondaryDatabaseConfig {} ○​ After successful login, a token is
generated and returned to the client.
Q) How many ways can we implement ○​ The token is passed in the
security in Spring Boot?​ Authorization header for future
Answer: Spring Boot supports multiple ways to requests (Bearer <token>).
implement security depending on the ●​ Use case: RESTful APIs and stateless
application’s requirements. The most common applications.
methods include; ●​ Spring Boot Support: Custom
implementation with filters and token
validation logic using
1️⃣ Spring Security (Core Approach) OncePerRequestFilter.

●​ What it is: The standard and comprehensive


solution for securing Spring applications.
4️⃣ OAuth2 and OpenID Connect
●​ Features:
○​ Authentication and Authorization ●​ What it is:
○​ CSRF Protection ○​ OAuth2: Provides delegated
○​ HTTP Basic authorization (e.g., allow GitHub to
○​ Form-based login access your calendar).​
○​ JWT
○​ OpenID Connect: An identity layer Q) How to configure Spring Security in Spring
built on OAuth2 (used for Single Boot?​
Sign-On). Answer:​
●​ Spring Boot Integration:
Use the spring-boot-starter-security
○​ Spring Boot provides
dependency to enable authentication and
spring-security-oauth2-clie
📦
authorization.​
nt and Example dependency:
spring-security-oauth2-reso
urce-server for easy integration. xml
●​ Use case: Third-party login (Google, <dependency>
Facebook, GitHub) or internal SSO systems. <groupId>[Link]</group
Id>
5️⃣ LDAP Authentication <artifactId>spring-boot-starter-security
</artifactId>
●​ What it is: Uses Lightweight Directory </dependency>
Access Protocol to authenticate users against
directory services (e.g., Active Directory). It provides default security settings such as basic login
●​ Use case: Enterprise applications with and CSRF protection. You can override these via
centralized user directories. configuration classes.
●​ Spring Boot Support:
○​ Via
Q) What is @EnableWebSecurity
spring-boot-starter-securit
annotation?​
y and configuring LDAP properties.
Answer:​
@EnableWebSecurity enables Spring
6️⃣ Form-Based Authentication Security’s web security support. It triggers
automatic security configuration, allowing you to
●​ What it is: Traditional login page with form
customize:
submission for authentication.
●​ Spring Boot Support:​
●​ Authentication
○​ Easily configured using ●​ Authorization
[Link]() in the security ●​ CSRF
configuration. ●​ CORS, etc.
○​ You can use the default login page
or create a custom login controller + Q) How do you handle authentication and
HTML page. authorization in Spring Boot?​
Answer:
7️⃣ Method-Level Security
●​ Authentication: Can be done using:
●​ What it is: Security enforced directly at the ○​ Username/password (form login or
method level using annotations. basic)
●​ Common Annotations: ○​ JWT tokens
○​ @PreAuthorize("hasRole('ADM ○​ OAuth2 (SSO or third-party login)
○​ LDAP
IN')")
●​ Authorization: Can be implemented by:
○​ @PostAuthorize, @Secured, and ○​ Role-based access control in
@RolesAllowed HttpSecurity
●​ Enable it using: @EnableMethodSecurity ○​ Annotations like @PreAuthorize,
or@EnableGlobalMethodSecurity(preP @Secured, or @RolesAllowed​
ostEnabled = true) depending on Spring
version.
Q) How to configure form-based login in Q) How to test service layers in Spring Boot?​
Spring Boot?​ Answer:​
Answer:​ Mock repository or external service dependencies
Use formLogin() in the security configuration class. using @MockBean and write unit tests using JUnit +
Mockito.
java
@Override @SpringBootTest
protected void configure(HttpSecurity public class UserServiceTest {
http) throws Exception { @MockBean
http private UserRepository
.authorizeRequests().anyRequest().authen userRepository;
ticated()
.and() @Autowired
private UserService userService;
.formLogin().loginPage("/login").permitA
ll(); // Test cases here
}​ }
You can use Spring's default login page or
customize your own. Q) How do you handle exceptions in Spring
Boot?​
Q) What is @SpringBootTest used for?​ Answer:
Answer:​
●​ Global Exception Handling: Use
@SpringBootTest loads the entire Spring
@ControllerAdvice with
Boot application context for integration testing.
@ExceptionHandler.
It is useful when testing how different layers
●​ Local Handling: Use @ExceptionHandler
(controller, service, repository) interact together.
inside the controller.

Q) How do you test a REST controller in @ControllerAdvice


Spring Boot?​ public class GlobalExceptionHandler {
Answer: @ExceptionHandler([Link])
public ResponseEntity<String>
●​ Use @WebMvcTest for unit testing only the handleException(Exception ex) {
controller layer. return new
●​ Use @SpringBootTest with a real or ResponseEntity<>([Link](),
embedded server for integration testing.​ HttpStatus.INTERNAL_SERVER_ERROR);
@WebMvcTest([Link])​ }
public class UserControllerTest {​ }

@Autowired​
Q) What is Spring Cloud and how does it
private MockMvc mockMvc;}
integrate with Spring Boot?​
Spring Cloud provides tools to build microservices by
Q) What is @MockBean used for in Spring
offering features like service discovery (Eureka),
Boot?​ configuration management (Config Server), circuit
Answer:​ breakers (Hystrix or Resilience4J), API gateways
@MockBean is used to mock dependencies (Spring Cloud Gateway), and more. It integrates
(like services or repositories) in the Spring seamlessly with Spring Boot for distributed, resilient
application context during tests. It replaces the systems.
real bean with a mock version (typically using
Mockito).
Q) How do you use Spring Boot with Eureka public class SchedulerApp {}
for service discovery?​
Add the following dependency: @Scheduled(fixedRate = 5000)
public void printTime() {
<dependency> [Link]("Running every 5
<groupId>[Link]</grou seconds");
pId> }
<artifactId>spring-cloud-starter-netflix
-eureka-client</artifactId> Q) What is the default logging framework in Spring
</dependency> Boot?​
Spring Boot uses Logback as the default logging
Then, enable discovery using: framework. It can be configured using
[Link] or XML-based
@EnableDiscoveryClient [Link].
@SpringBootApplication
public class MyServiceApplication {} Q) How do you enable SSL in Spring Boot?​
Configure the following properties:
Q) How to configure Spring Boot with Kafka?​
Use the Spring Kafka starter dependency: properties
[Link]=8443
<dependency> [Link]-store=classpath:keystore.
<groupId>[Link]</grou jks
pId> [Link]-store-password=your-passw
<artifactId>spring-kafka</artifactId> ord
</dependency> [Link]-store-type=JKS
[Link]-alias=your-alias
Configure Kafka in [Link]:
Q) What is the purpose of @ComponentScan in
properties Spring Boot?​
[Link]-servers=localhost @ComponentScan tells Spring where to look for
:9092 components, such as @Service, @Repository,
[Link]-id=my-group @Controller, etc. It's automatically included in
@SpringBootApplication, scanning the base
Q) How does Spring Boot support Docker?​ package and sub-packages.
Spring Boot applications can be containerized using
Docker by: Q) How to handle asynchronous processing in
Spring Boot?​
●​ Creating a Dockerfile to define how to build Use @EnableAsync to enable async processing, and
the image. @Async to mark a method for async execution.
●​ Using spring-boot-maven-plugin to
build Docker images.​ @Configuration
This enables consistent deployment across
@EnableAsync
environments.
public class AsyncConfig {}
Q) How to schedule tasks in Spring Boot?​ @Service
Use @EnableScheduling on a configuration class public class MyService {
and annotate methods with @Scheduled.​ @Async
@EnableScheduling​ public CompletableFuture<String>
@SpringBootApplication processTask() {
return Q) How to implement basic authentication in
[Link]("Task Spring Boot?​
completed"); Configure HTTP Basic security using:

}
@Override
}
protected void configure(HttpSecurity
Q) What is Spring Security?​ http) throws Exception {
Spring Security is a robust framework for securing [Link]().and().authorizeRequests
Java applications. It provides authentication, ().anyRequest().authenticated();
authorization, CSRF protection, and integrates with ​
various protocols (LDAP, OAuth2, JWT, etc.). Q) How to configure a message broker in Spring
Boot?​
Q) How to enable Spring Security in a Spring Boot A: You can configure a message broker, such as
application?​ RabbitMQ or Kafka, by adding the required starter
Add the dependency: dependencies and application properties.​
Example (RabbitMQ Dependency):
<dependency> <dependency>
<groupId>[Link]</group <groupId>[Link]</groupId>
<artifactId>spring-boot-starter-amqp</artifac
Id>
tId>
<artifactId>spring-boot-starter-security
</dependency>
</artifactId>
</dependency> Q) How do you send and receive messages with
RabbitMQ in Spring Boot?​
Q) What is the default username and password in A: Use @RabbitListener for consuming messages
Spring Security?​
and RabbitTemplate for sending messages.
The default username is user, and the password is
auto-generated at runtime and printed in the console @RabbitListener(queues = "queueName")
log. public void receiveMessage(String message) {
[Link]("Received: " + message);
Q) How to configure a custom login page in Spring
}
Security?​
@Autowired
You can use the .formLogin() method in the private RabbitTemplate rabbitTemplate;
configure(HttpSecurity http) method:
public void sendMessage(String message) {
@Override [Link]("queueName",
protected void configure(HttpSecurity message);
http) throws Exception { }
[Link]().loginPage("/login").per
Q) What is Spring Kafka and how is it used in
mitAll();
Spring Boot?​
}
A: Spring Kafka provides integration with Apache
Kafka, simplifying message publishing and
Q) What is method-level security in Spring consumption in Spring Boot applications.​
Security?​ Example Dependency:​
It allows restricting access at method level using
<dependency>
annotations like @PreAuthorize, @Secured.
<groupId>[Link]</grou
pId>​
@PreAuthorize("hasRole('ADMIN')")
<artifactId>spring-kafka</artifactId>​
public void deleteUser() {}
</dependency>
Q) How do you configure a Kafka producer and Q) How do you use Spring Cloud Eureka for
consumer in Spring Boot?​ service discovery?​
A: Configure Kafka properties in A: Add the
[Link].​ spring-cloud-starter-netflix-eureka-clie
Example:​ nt dependency and annotate the application with
[Link]-servers=localhost:9092​ @EnableDiscoveryClient.​
[Link]-id=test-group <dependency>
<groupId>[Link]</groupId>​
Q) What is Reactive Programming in Spring Boot?​ <artifactId>spring-cloud-starter-netflix-eure
A: Reactive programming is a paradigm for handling ka-client</artifactId> </dependency>
asynchronous data streams. In Spring Boot, it's
supported by Spring WebFlux for building non-blocking Q) What is Spring Cloud Config?​
applications. A: Spring Cloud Config provides centralized
configuration management for distributed systems.
Q) What is Spring WebFlux?​
A: Spring WebFlux is a reactive web framework that [Link]=[Link]
enables non-blocking and asynchronous request
rver:8888
handling.
Q) How do you configure Spring Boot with Spring
Q) What are Mono and Flux in Spring WebFlux?​
Cloud Config Server?​
A: Mono represents 0 or 1 value; Flux represents 0
A: Use @EnableConfigServer in a Spring Boot
to N values asynchronously.
application.
Mono<String> mono = [Link]("Hello");
@SpringBootApplication
Flux<String> flux = [Link]("Hello",
@EnableConfigServer
"World");
public class ConfigServerApplication {
public static void main(String[] args) {
Q64) How to use @GetMapping in Spring
[Link](ConfigServerApplication
WebFlux?​
.class, args); } }
A: Use @GetMapping in a reactive controller to return
Mono or Flux.​ Q) What is Spring Cloud Gateway and how is it
@RestController​ used with Spring Boot?​
public class WebFluxController {​ A: It acts as an API gateway to route requests to
@GetMapping("/mono")​ different microservices.
public Mono<String> getMono() {​
return [Link]("Hello, Reactive World!");​ <dependency>
} } <groupId>[Link]</groupId>
<artifactId>spring-cloud-starter-gateway</art
Q) How do you handle exceptions in WebFlux?​ ifactId>
A: Use @ExceptionHandler in the controller or a </dependency>
global handler via @ControllerAdvice.
Q) How do you implement load balancing in Spring
Q) What is @ResponseStatus in WebFlux?​ Boot with Spring Cloud?​
A: It is used to annotate methods or exceptions to A: Use Ribbon with @LoadBalanced on a
return specific HTTP status codes. RestTemplate bean.​
@LoadBalanced​
Q) What is Spring Cloud?​
@Bean ​
A: Spring Cloud is a set of tools that help in building
public RestTemplate restTemplate() {​
and managing microservices, offering solutions like
service discovery, config management, circuit return new RestTemplate();
breakers, load balancing, etc.
}
Q) What is validation in Spring public class UserRequest {
@Email(message = "Must be a valid
Boot and how is it supported?​
email!")
A: Spring Boot supports validation private String email;
using JSR-380 (Jakarta Bean Validation, }
formerly [Link]). It enables
automatic input validation for REST API 3. @Size(min, max)
requests or form data using annotations Purpose: Validates that a string/collection
like @NotNull, @Email, @Min, etc. It has a length/size between min and max.​
integrates with Spring via @Valid and Use Cases:
@Validated. ●​ Password length constraints.
●​ Limiting list/array size.​
Q) What dependency is required for Example:
java
bean validation in Spring Boot?​ public class UserRequest {
A: You need the @Size(min = 6, max = 20, message =
spring-boot-starter-validation "Password must be 6-20 characters!")
private String password;
dependency. It brings in Hibernate
Validator, which is the reference @Size(max = 10, message = "Cannot
implementation of JSR-380. select more than 10 items!")
private List<String> preferences;
<dependency>​ }
<groupId>[Link]</group
Id> Other Key Annotations
<artifactId>spring-boot-starter-validati
Annot Purpose Example
on</artifactId> </dependency> ation

Q) What are commonly used bean


@NotN Field must not @NotNull
validation annotations in Spring
ull be null private String
Boot?​ name;
1. @NotBlank
Purpose: Validates that a string field is not​ @NotE @NotEmpty
Field must not
null, empty, or whitespace-only.​ mpty be null or List<String>
Use Case: empty items;
●​ Mandatory fields like usernames,
passwords, etc.​
@Min / Numeric value @Min(18)
Example:
java @Max constraints private int
public class UserRequest { age;
@NotBlank(message = "Username cannot be
blank!") @Patt Regex @Pattern(regex
private String username; ern p =
validation
}
"^[A-Za-z]+$")

2. @Email
Purpose: Validates that a string is a How to Enable Validation in Spring
well-formed email address.​ Boot?
Use Case: 1.​ Add the validation starter (if not
●​ Email fields in registration forms.​ already present):
Example: <dependency>
java <groupId>[Link]</groupId>
<artifactId>spring-boot-starter-validation< Q) What is the difference between
/artifactId>
@Valid and @Validated in Spring
2.​ </dependency>
Boot?
3.​ Use @Valid in controller methods:
@PostMapping("/users")
public ResponseEntity<String> ●​ @Valid: Used on method parameters
createUser(@Valid @RequestBody UserRequest (e.g., in a controller) to trigger
user) { validation based on constraints.
return [Link]("Valid!"); ●​ @Validated: Supports validation
4.​ }
groups and method-level
5.​ Handle validation errors globally validation, typically used at
(using @ControllerAdvice):​ class level.​
@ExceptionHandler(MethodArgumentNotValidExc
[Link])
public ResponseEntity<Map<String, String>> Example with @Valid:​
handleValidationExceptions( @RestController​
MethodArgumentNotValidException ex) { @RequestMapping("/users")​
Map<String, String> errors = new
public class UserController {
HashMap<>();
@PostMapping​
[Link]().getAllErrors().forEac public ResponseEntity<String>
h(error -> { addUser(@Valid @RequestBody User user) {​
String fieldName = ((FieldError)
return [Link]("User is
error).getField();
String message = valid"); } }
[Link]();
[Link](fieldName, message); Example with @Validated:​
}); @Validated​
return
@Service​
[Link]().body(errors); }
public class PaymentService {​
@Min Annotation public void process(@Min(100) int
Purpose: Ensures a numeric value is greater amount) {​
than or equal to the specified minimum.​ // Only processes if amount >= 100 } }
Applicable Types:
●​ int, long, short, BigDecimal, Q) What happens if validation fails when
BigInteger, etc. using @Valid in a controller?​
Example: Age Validation A: Spring Boot will automatically
public class Employee { return a 400 Bad Request along with
@Min(value = 18, message = "Age must be validation error details in the response
at least 18!")
body.
private int age;
}
Q) How do you create a custom validator
@Max Annotation in Spring Boot?​
Purpose: Ensures a numeric value is less A: Create a new annotation and its
than or equal to the specified maximum. associated validator class.
Example: Salary Validation
public class Employee { Step 1: Create the custom annotation​
@Max(value = 100000, message = "Salary
@Constraint(validatedBy =
cannot exceed $100,000!")
private double salary; [Link])​
} @Target({ [Link] })
@Retention([Link])​ Q) What is the use of @Cacheable annotation
public @interface ValidUsername {​ in Spring Boot?​
String message() default "Invalid A) The @Cacheable annotation marks a method's
username";​ return value to be cached. If the method is called again
Class<?>[] groups() default {};​ with the same parameters, the cached result is
Class<? extends Payload>[] payload() returned instead of executing the method again.
default {};
@Cacheable("products")​
}​ public Product getProductById(Long id) {
Step 2: Implement the validator logic simulateSlowService(); // e.g., DB call​
return
public class UsernameValidator [Link](id).orElse(nu
implements ll);
ConstraintValidator<ValidUsername,
String> { }​
products is the cache name. On the first call, the
@Override​ method runs and the result is cached. Subsequent
public boolean isValid(String value, calls with the same id return the cached result.
ConstraintValidatorContext context) {
Q) What is the use of @CacheEvict
return value != null && annotation in Spring Boot?​
[Link]("^[a-zA-Z0-9_]{5,20}$"); } A) The @CacheEvict annotation removes an entry
}​ from the cache. It's typically used when data
changes and the cache must be updated.
Step 3: Use the annotation in your model

@CacheEvict(value = "products", key =


public class User {​
"#id")
@ValidUsername​
private String username; }
public void deleteProduct(Long id) {
[Link](id); }
Q) What is caching in Spring Boot and why is
it important?​
Q) What are the common cache providers
A) Caching is a technique to improve application
supported by Spring Boot?​
performance by storing frequently accessed data in
A) Spring Boot supports pluggable cache
memory or external storage. In Spring Boot, caching is
providers including:
supported with annotations and multiple providers like
Ehcache, Caffeine, and Redis. It helps reduce
●​ Ehcache – in-memory, Java-based caching
expensive calls (like DB queries or remote APIs).
●​ Caffeine – high-performance, Java-based
caching
Q) How do you enable caching in a Spring
●​ Redis – distributed in-memory cache, ideal
Boot application?​ for microservices
A) Use the @EnableCaching annotation on your
main application class.​ Q84) How do you configure Ehcache with Spring
@SpringBootApplication​ Boot?
@EnableCaching​
public class MyApp {​ ●​ Add dependency:​
public static void main(String[] args) <dependency>
{ [Link]([Link], args); <groupId>[Link]</groupId>​
<artifactId>ehcache</artifactId>​
} } </dependency>
●​ Example configuration ([Link]): ArrayList is implemented as a resizable array (i.e., a
dynamic array). Internally, it uses an array to store the
elements.
<config>​
<cache alias="products">​
<heap>1000</heap>​
🔧 Internal Working:
</cache>​ ●​ It maintains an Object[] elementData array.
</config> ●​ When elements are added and the current array
is full, it creates a new array with a larger size
(usually 1.5 times the current size) and copies
Q) How do you configure Caffeine with Spring
old elements into the new one.
Boot? ●​ All elements are stored in contiguous memory

●​ Add dependency:
●​
🚩 Drawbacks:
locations​

Slower when inserting/deleting from the middle


<dependency> (requires shifting).
<groupId>[Link]</ ●​ May use more memory during resize due to
array duplication.
groupId>
<artifactId>caffeine</artifactId>​
</dependency>
✅ Q) How does LinkedList work
internally in Java?​
●​ Set properties in LinkedList is implemented as a doubly linked list. It
consists of nodes where each node contains data and

🔧 Internal Working:
[Link]:
pointers to the next and previous nodes.​

[Link]=caffeine​
[Link]=maximumSize=1
000,expireAfterAccess=5m ●​ It has an internal class called Node<E> with
data, next, and prev references.
●​ The list maintains references to the first and
Q) How do you configure Redis as a cache
last nodes.
provider in Spring Boot? ●​ Elements are not stored in contiguous memory,
and memory is allocated for each node
●​ Add dependency: separately.

<dependency> **********IMP​
<groupId>[Link]</group @RestController​
@RequestMapping("/api/employees")​
Id>
public class EmployeeController {​
<artifactId>spring-boot-starter-data-red ​ private final List<String> employeeNames =
is</artifactId>​ [Link](​
​ "John Doe","Jane Smith", "Alice Johnson",
</dependency>
"Bob Martin"};

●​ Configure properties:​ ​
[Link]=redis​ @GetMapping("/names")​
[Link]=localhost​ public ResponseEntity<List<String>>
getEmployeeNames() {​
[Link]=6379
return [Link](employeeNames); // HTTP 200
with body } }​
Redis is suitable for distributed caching in ​
microservices environments. @PostMapping("/add")​

✅ Q) How does ArrayList work


public ResponseEntity<String>
addEmployee(@RequestBody Employee employee) {​
​ String response = "Employee added: " +
[Link](); return
internally in Java? [Link](response); // HTTP 200 with message​
}
*******The
Producer-Consumer Problem is a classic public Producer(SharedBuffer buffer)
example of a multi-threading synchronization {
problem. It involves: [Link] = buffer;
}
●​ Producer: Produces data and puts it into a
shared resource (like a buffer/queue). public void run() {
●​ Consumer: Consumes data from the int value = 0;
shared resource. try {
●​ Problem: Proper synchronization is while (true) {
required so the producer doesn’t add data [Link](value++);
when the buffer is full, and the consumer [Link](500);
doesn’t try to consume when the buffer is }
empty. } catch (InterruptedException e)
{

✅ Goals }
[Link]();

}
●​ Synchronize access to the shared buffer. }

👷 Consumer Thread
●​ Prevent race conditions.
●​ Use wait-notify mechanism or modern
BlockingQueue.
class Consumer extends Thread {

✅ Solution 1: Using wait() and private final SharedBuffer buffer;

public Consumer(SharedBuffer buffer)


notify() (Low-Level)
{

🔧 Shared Resource: Bounded Buffer (List with size limit) }


[Link] = buffer;

import [Link];​
import [Link];​ public void run() {
class SharedBuffer {​
try {
​ private final Queue<Integer> queue =
while (true) {
new LinkedList<>();​
​ private final int capacity = 5; [Link]();
public synchronized void produce(int value) [Link](1000);
throws InterruptedException {​ }
while ([Link]() == capacity) { } catch (InterruptedException e)
wait(); // wait until not full​ {
} [Link](value);​ [Link]();
​ [Link]("Produced: " +
}
value);​
}
notify(); // notify consumer } ​
​ }
​ public synchronized void consume()
throws InterruptedException {​
​ while ([Link]()) {​
🚀 Main Class
​ wait(); // wait until not empty }​ public class ProducerConsumerDemo {
​ int value = [Link](); public static void main(String[]
[Link]("Consumed: " + args) {
value);​ SharedBuffer buffer = new
notify(); // notify producer } } SharedBuffer();

👷 Producer Thread Producer producer = new


Producer(buffer);
class Producer extends Thread { Consumer consumer = new
private final SharedBuffer buffer; Consumer(buffer);
[Link](); [Link]().interrupt();
[Link](); }
} };
}
new Thread(producer).start();

✅ Output (sample) }
new Thread(consumer).start();

Produced: 0 }
Consumed: 0
Produced:
Produced:
Consumed:
1
2
1 …….
🔍 What does "statically typed"
mean?

✅ Alternative: Use BlockingQueue In a statically typed language, the type of a variable is


known at compile-time, and you must declare the type
(High-Level, Thread-safe)
explicitly.

✅ Example in Java:
import [Link].*;

public class BlockingQueueExample {


public static void main(String[] int number = 10; // 'number' is
args) { of type int
BlockingQueue<Integer> queue = String name = "Alice"; // 'name' is of
new ArrayBlockingQueue<>(5); type String​
​ If you try to assign a String to number,
Runnable producer = () -> {


the compiler will throw an error.
int value = 0;
number = "Hello"; // Compile-time
try {
while (true) { error
[Link](value);

[Link]("Produced: " +
🔁 Comparison: Dynamically Typed
Languages
value++);
[Link](500); Languages like Python or JavaScript are dynamically
} typed, meaning variable types are determined at
} catch runtime, and type mismatches are only caught when
(InterruptedException e) { the code is run.​
x = 10 # int​
[Link]().interrupt();
x = "hello" # now a string - allowed at
}
runtime.
};

Runnable consumer = () -> { 🔒 Why static typing helps?


try {
while (true) { ●​ Early error detection
int val = ●​ Better performance
[Link](); ●​ IDE auto-completion
●​ Code maintainability
[Link]("Consumed: " + val);
[Link](1000);
}
} catch
(InterruptedException e) {
✅ 1. Java is Statically Typed
●​ Variable types are known at compile-time.
●​ You must declare types explicitly (or
inferred with var in Java 10+).
●​ Type checks happen during compilation,
not runtime.

✅ 2. Java is Strongly Typed


●​ Once a variable is assigned a type, you
can’t treat it as another type without
explicit casting.
●​ It doesn’t allow operations between
mismatched types.

int a = 5;
String b = "test";
int result = a + b; // ❌ Compile-time
error​
​ Even if Java allows casting, it’s explicit
and controlled, unlike weakly typed languages.

You might also like