Java Interview Prep Handbook
Java Interview Prep Handbook
Detailed Explanation
1. Encapsulation
Encapsulation is the mechanism of wrapping data (variables) and code acting on the data (methods)
into a single unit (class) and restricting direct access to some of the object's components.
public class BankAccount {
private double balance; // private = hidden from outside
private String accountId;
2. Abstraction
Abstraction hides implementation complexity and exposes only the essential features. Achieved via
abstract classes and interfaces.
public interface PaymentGateway {
boolean processPayment(double amount); // what it does, not how
void refund(String transactionId);
}
3. Inheritance
Inheritance allows a class (child) to acquire properties and behaviours of another class (parent),
enabling code reuse.
public class Animal {
protected String name;
public void eat() { [Link](name + " is eating"); }
}
4. Polymorphism
Polymorphism means 'many forms'. Java supports compile-time polymorphism (method overloading)
and runtime polymorphism (method overriding).
// Runtime Polymorphism
Animal animal = new Dog(); // reference type = Animal
[Link](); // calls Dog's overridden version at runtime
⚠️Common Mistakes
Confusing abstraction with encapsulation — encapsulation hides data; abstraction hides
complexity.
Saying Java supports multiple inheritance — Java supports multiple inheritance of TYPE
(interfaces), not STATE.
Forgetting to say polymorphism requires IS-A relationship.
❓ Interview Question
What is the difference between an Interface and an Abstract Class?
// Interface example
public interface Flyable {
void fly();
default void land() { [Link]("Landing..."); } // Java 8
}
❓ Interview Question
Why is String immutable in Java? What are the benefits?
Detailed Explanation
String immutability is enforced in the [Link] class:
// Simplified internal view of String class
public final class String {
private final char[] value; // final + private = truly immutable
private int hash; // cached hashcode
...
}
⚠️Common Mistakes
Using == for String comparison in production — classic bug.
Not knowing String Pool moves to Heap in Java 8 (from PermGen).
Forgetting StringBuilder / StringBuffer for mutable string operations in loops.
❓ Interview Question
How does HashMap work internally in Java?
Java 8 Treeification
When a bucket has 8+ nodes, it converts from LinkedList to a Red-Black Tree, improving worst-case
lookup from O(n) to O(log n). It converts back to LinkedList when size drops to 6.
⚠️Common Mistakes
Not implementing hashCode() when overriding equals() — breaks HashMap contract!
Using mutable objects as HashMap keys — if key state changes, you can't retrieve the
value.
Assuming HashMap is ordered — it is NOT. Use LinkedHashMap for insertion order,
TreeMap for sorted order.
❓ Interview Question
What is the difference between HashMap, LinkedHashMap, TreeMap, and
ConcurrentHashMap?
❓ Interview Question
How does ConcurrentHashMap work internally?
// Atomic operations
[Link]("key", 2); // atomic
[Link]("key", k -> [Link]()); // atomic
[Link]("key", 1, Integer::sum); // atomic increment
❓ Interview Question
What is the difference between ArrayList and LinkedList?
❓ Interview Question
What is the contract between equals() and hashCode()?
// CORRECT implementation
public class Employee {
private int id;
private String name;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Employee)) return false;
Employee e = (Employee) o;
return id == [Link] && [Link](name, [Link]);
}
@Override
public int hashCode() {
return [Link](id, name); // same fields as equals()
}
}
❓ Interview Question
Explain Lambda expressions and Functional Interfaces.
// Functional Interface
@FunctionalInterface
interface MathOperation {
int operate(int a, int b); // single abstract method
}
// Lambda usage
MathOperation add = (a, b) -> a + b;
MathOperation multiply = (a, b) -> a * b;
[Link]([Link](5, 3)); // 8
[Link]([Link](5, 3)); // 15
❓ Interview Question
Explain the Stream API with examples.
// Group by department
Map<String, List<Employee>> byDept = [Link]()
.collect([Link](Employee::getDepartment));
// flatMap example
List<List<Integer>> nested = [Link]([Link](1,2),
[Link](3,4));
List<Integer> flat = [Link]()
.flatMap(Collection::stream) // [1,2,3,4]
.collect([Link]());
// map vs flatMap
List<String> words = [Link]("Hello World", "Java Stream");
// map gives Stream<String[]>
[Link]().map(s -> [Link](" "));
// flatMap gives Stream<String>
[Link]().flatMap(s -> [Link]([Link](" "))); //
[Hello,World,Java,Stream]
❓ Interview Question
What is Optional in Java 8 and how do you use it?
// Creating Optional
Optional<String> opt1 = [Link]("value"); // throws NPE if null
Optional<String> opt2 = [Link](null); // empty Optional
Optional<String> opt3 = [Link](); // explicitly empty
// Using Optional
String result = [Link]("default"); // "value"
String result2 = [Link]("default"); // "default"
String result3 = [Link](() -> computeDefault()); // lazy
[Link](() -> new EntityNotFoundException()); // throw if empty
// Chaining
Optional<String> upper = opt1
.filter(s -> [Link]() > 3)
.map(String::toUpperCase);
// In service layer
public Optional<User> findUserById(Long id) {
return [Link](id); // Spring Data returns Optional
}
// In controller
User user = [Link](id)
.orElseThrow(() -> new UserNotFoundException("User not found: " + id));
⚠️Common Mistakes
Using Optional as method parameters — anti-pattern. Use overloads instead.
Calling [Link]() without isPresent() — defeats the purpose.
Using Optional for collection return types — return empty collection instead.
Serializing Optional fields — Optional is not Serializable.
CHAPTER 2: JVM INTERNALS & MEMORY MODEL
⚠️Common Mistakes
Calling [Link]() in production — just a hint, JVM may ignore it, causes full GC if
executed.
Memory leaks in Java are possible! Static collections, thread-local variables, unclosed
resources, listeners.
Not setting -Xmx in containers — JVM may take all container memory leading to OOM kill.
2.3 Multithreading & Concurrency
❓ Interview Question
What is the difference between synchronized, volatile, and ReentrantLock?
❓ Interview Question
What are common concurrency issues and how do you prevent them?
❓ Interview Question
Explain Spring Bean lifecycle.
@Component
public class MyBean implements InitializingBean, DisposableBean {
❓ Interview Question
What are Spring Bean Scopes?
⚠️Common Mistakes
Injecting prototype bean into singleton bean — prototype won't work as expected (only one
instance created).
Fix: use [Link](), @Lookup annotation, or ObjectProvider<T>.
Putting state in singleton beans — not thread-safe! Singletons are shared across all threads.
❓ Interview Question
What is the difference between @Component, @Service, @Repository, and @Controller?
❓ Interview Question
How does @Transactional work internally?
⚠️Common Mistakes
Self-invocation: calling @Transactional method from same class bypasses the proxy —
transaction NOT applied!
Fix: inject self reference, or use AspectJ mode.
@Transactional on private methods — does NOT work (proxy can't intercept private
methods).
Default rollback only on RuntimeException — checked exceptions do NOT trigger rollback by
default.
Use rollbackFor = [Link] to rollback on checked exceptions too.
@SpringBootApplication
// Equivalent to:
// @Configuration + @EnableAutoConfiguration + @ComponentScan
❓ Interview Question
How do you design a RESTful API for a User resource?
@GetMapping
public ResponseEntity<Page<UserDTO>> getUsers(
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "20") int size,
@RequestParam(required = false) String search) {
return [Link]([Link](page, size, search));
}
@GetMapping("/{id}")
public ResponseEntity<UserDTO> getUser(@PathVariable Long id) {
return [Link](id)
.map(ResponseEntity::ok)
.orElseThrow(() -> new ResourceNotFoundException("User", id));
}
@PostMapping
public ResponseEntity<UserDTO> createUser(@Valid @RequestBody
CreateUserRequest req) {
UserDTO created = [Link](req);
URI location = [Link]("/api/v1/users/" + [Link]());
return [Link](location).body(created);
}
@PatchMapping("/{id}")
public ResponseEntity<UserDTO> updateUser(
@PathVariable Long id,
@Valid @RequestBody UpdateUserRequest req) {
return [Link]([Link](id, req));
}
@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteUser(@PathVariable Long id) {
[Link](id);
return [Link]().build();
}
}
❓ Interview Question
How do you implement global exception handling in Spring Boot?
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler([Link])
public ResponseEntity<ErrorResponse> handleNotFound(ResourceNotFoundException
ex) {
return [Link](HttpStatus.NOT_FOUND)
.body(new ErrorResponse("NOT_FOUND", [Link]()));
}
@ExceptionHandler([Link])
public ResponseEntity<ErrorResponse>
handleValidation(MethodArgumentNotValidException ex) {
List<String> errors = [Link]().getFieldErrors()
.stream()
.map(e -> [Link]() + ": " + [Link]())
.collect([Link]());
return [Link]()
.body(new ErrorResponse("VALIDATION_FAILED", [Link]()));
}
@ExceptionHandler([Link])
public ResponseEntity<ErrorResponse> handleGeneral(Exception ex) {
[Link]("Unexpected error", ex);
return [Link](HttpStatus.INTERNAL_SERVER_ERROR)
.body(new ErrorResponse("INTERNAL_ERROR", "An unexpected error
occurred"));
}
}
@Data @AllArgsConstructor
public class ErrorResponse {
private String code;
private String message;
private Instant timestamp = [Link]();
}
CHAPTER 5: DATABASE, JPA & HIBERNATE
❓ Interview Question
Explain Hibernate Persistence Context and Entity States.
// REMOVED
[Link]([Link](user)); // merge then remove
}
❓ Interview Question
What is the N+1 problem and how do you fix it?
// Fix 2: @EntityGraph
@EntityGraph(attributePaths = {"customer", "items"})
@Query("SELECT o FROM Order o")
List<Order> findAllWithDetails();
❓ Interview Question
What is the difference between EAGER and LAZY loading?
❓ Interview Question
What are the key patterns in microservices?
• Saga Pattern
• Manages distributed transactions across services. Choreography (events) vs Orchestration
(central coordinator).
# [Link]
resilience4j:
circuitbreaker:
instances:
paymentService:
slidingWindowSize: 10
failureRateThreshold: 50
waitDurationInOpenState: 30s
❓ Interview Question
How do microservices communicate with each other?
@Component
public class InventoryEventConsumer {
@KafkaListener(topics = "order-events", groupId = "inventory-service")
public void handleOrderCreated(OrderCreatedEvent event) {
[Link]([Link]());
}
}
CHAPTER 7: SPRING SECURITY & API SECURITY
❓ Interview Question
How do you implement JWT-based authentication in Spring Boot?
// JWT Filter
@Component
public class JwtAuthFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest req, HttpServletResponse
res,
FilterChain chain) throws ServletException, IOException {
String header = [Link]("Authorization");
if (header == null || ) {
[Link](req, res); return;
}
String token = [Link](7);
try {
Claims claims = [Link](token);
UsernamePasswordAuthenticationToken auth =
new UsernamePasswordAuthenticationToken(
[Link](), null,
[Link]([Link]("roles")));
[Link]().setAuthentication(auth);
} catch (JwtException e) {
[Link]([Link]()); return;
}
[Link](req, res);
}
}
// Security Config
@Configuration @EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http
.csrf(csrf -> [Link]()) // stateless — no CSRF needed
.sessionManagement(s ->
[Link]([Link]))
.authorizeHttpRequests(auth -> auth
.requestMatchers("/api/auth/**").permitAll()
.requestMatchers("/api/admin/**").hasRole("ADMIN")
.anyRequest().authenticated())
.addFilterBefore(jwtAuthFilter,
[Link])
.build();
}
}
@Service
@CacheConfig(cacheNames = "users")
public class UserService {
# Redis configuration
[Link]=redis
[Link]=localhost
[Link]=6379
[Link]-to-live=30m
❓ Interview Question
What are the most important design patterns for Java backend interviews?
Design patterns are categorized as Creational, Structural, and Behavioral. Focus on patterns used in
Spring itself.
Category Pattern Java/Spring Usage
Creational Singleton Spring singleton beans,
[Link]
Creational Factory Method BeanFactory,
[Link]()
Creational Builder StringBuilder,
[Link], Lombok
@Builder
Creational Prototype Spring prototype scope,
[Link]()
Structural Proxy Spring AOP, @Transactional,
@Cacheable
Structural Decorator InputStream wrapping, Spring
Security filters
Structural Adapter [Link](),
InputStreamReader
Behavioral Observer/Event ApplicationEvent, Kafka
consumers
Behavioral Template Method JdbcTemplate, RestTemplate
Behavioral Strategy Comparator, sorting algorithms
Behavioral Chain of Responsibility Servlet filters, Spring Security
filter chain
// Builder Pattern — production style
@Builder @Data
public class EmailRequest {
private String to;
private String subject;
private String body;
private List<String> cc;
private boolean isHtml;
}
// Usage: clean, readable, immutable
EmailRequest req = [Link]()
.to("user@[Link]")
.subject("Welcome!")
.body("<h1>Hello</h1>")
.isHtml(true)
.build();
// Strategy Pattern
public interface DiscountStrategy {
Category Pattern Java/Spring Usage
double apply(double price);
}
public class SeasonalDiscount implements DiscountStrategy {
public double apply(double price) { return price * 0.85; }
}
public class LoyaltyDiscount implements DiscountStrategy {
public double apply(double price) { return price * 0.90; }
}
// PricingService takes strategy — open for extension, closed for modification
(OCP)
CHAPTER 10: SCENARIO-BASED & PRODUCTION
QUESTIONS
Common Fixes
• DB: Add indexes, fix N+1 (JOIN FETCH), use read replicas, add caching.
• App: Use async processing, CompletableFuture for parallel calls, optimize serialization.
• Connection Pool: Increase pool size, tune checkout timeout.
• Caching: Add Redis cache for frequently-read data with low update frequency.
• Pagination: Avoid loading millions of records — use Pageable.
❓ Interview Question
Scenario: How would you handle duplicate API requests? (Idempotency)
@Service
public class IdempotentOrderService {
return response;
}
}
❓ Interview Question
Scenario: How would you implement rate limiting in a Spring Boot API?
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain
chain)
throws IOException, ServletException {
HttpServletRequest httpReq = (HttpServletRequest) req;
String clientIp = [Link]();
❓ Interview Question
Scenario: How do you handle database migration in production?
✅ Short Answer (For Interview)
Use Flyway or Liquibase. Migration scripts are versioned and run automatically on startup.
Always make migrations backward-compatible: add columns as nullable first, then fill data,
then add constraints.
-- V3__add_phone_index.sql
CREATE INDEX idx_users_phone ON users(phone);
# [Link]
[Link]=true
[Link]=classpath:db/migration
[Link]-on-migrate=true
CHAPTER 11: TOP 50 MOST ASKED INTERVIEW
QUESTIONS
This chapter provides a rapid-fire reference of the most commonly asked questions with concise
answers.
# Question Answer
1 What is the difference between == compares object references;
== and equals()? equals() compares content.
Always override equals() and
hashCode() together.
2 Can we override static No. Static methods belong to
methods? the class, not the instance. They
can be hidden (shadowed) in
subclass but not overridden —
no polymorphism.
3 What is the difference between final: modifier (immutable var,
final, finally, and finalize()? no-override method, no-extend
class). finally: block that always
executes. finalize(): deprecated
GC hook.
4 What is the difference between Checked: must be
checked and unchecked caught/declared (IOException,
exceptions? SQLException). Unchecked:
RuntimeException subclasses
(NPE,
IllegalArgumentException).
Spring recommends unchecked.
5 What is try-with-resources? Java 7 feature: resources
implementing AutoCloseable
are automatically closed.
Eliminates finally block for
cleanup.
6 What is a functional interface? Interface with exactly one
abstract method.
@FunctionalInterface
annotation enforces this.
Examples: Runnable,
Comparator, Callable,
Predicate.
7 What is method reference? Shorthand for lambda:
ClassName::methodName.
Types: static (Math::abs),
instance (str::length),
constructor (User::new),
arbitrary instance
(String::toUpperCase).
8 What is CompletableFuture? Java 8 async programming.
Supports chaining: thenApply
(transform), thenAccept
# Question Answer
(consume), thenCompose
(flatMap), allOf (wait all), anyOf
(first completed).
9 What is the difference between Comparable: natural ordering (in
Comparable and Comparator? class, compareTo). Comparator:
external ordering (outside class,
compare).
[Link]() for
chaining.
10 What are generics in Java? Type parameterization for
compile-time type safety.
Wildcards: ? extends T (read), ?
super T (write), ? (unknown).
Type erasure at runtime.
11 What is the difference between List<Object> only accepts
List<?> and List<Object>? List<Object>. List<?> accepts
any parameterized List. Use
wildcards for flexible APIs.
12 What is enum in Java? Type-safe constants. Can have
fields, constructors, methods.
Implicit Comparable,
Serializable.
EnumSet/EnumMap for
efficiency.
13 What is a record in Java 16? Immutable data carrier class.
Auto-generates constructor,
getters, equals, hashCode,
toString. Perfect for DTOs and
value objects.
14 What is a sealed class (Java Restricts which classes can
17)? extend/implement it. Uses
permits keyword. Enables
exhaustive pattern matching in
switch expressions.
15 What is var in Java 10? Local variable type inference.
var infers type from right-hand
side. Only for local variables,
not fields, parameters, or return
types.
16 What is the difference between Hashtable: synchronized (slow),
HashMap and Hashtable? no null keys/values, legacy.
HashMap: not synchronized,
allows one null key. Use
ConcurrentHashMap for thread
safety.
17 What is fail-fast vs fail-safe Fail-fast: throws
iterator? ConcurrentModificationExceptio
n if collection modified during
iteration (ArrayList). Fail-safe:
iterates on copy
(CopyOnWriteArrayList).
# Question Answer
18 What is the purpose of the Marks field to be excluded from
transient keyword? Java serialization. Use for
sensitive data (passwords),
derived fields, or non-
serializable objects.
19 What is reflection in Java? Inspect and modify class
structure at runtime. Used by
Spring (DI), JUnit, ORM
frameworks. Has performance
overhead — avoid in hot paths.
20 What is a ClassLoader? Loads .class files. Hierarchy:
Bootstrap → Extension
(Platform) → Application.
ClassLoader isolation used in
OSGi, containers, hot reload.
21 What is the difference between @Autowired is Spring-specific;
@Autowired and @Inject? @Inject is JSR-330 standard.
Both support
constructor/field/setter injection.
@Autowired has required
attribute.
22 What is @Value in Spring? Injects property values:
@Value("${[Link]}").
Supports SpEL:
@Value("#{[Link]
Role}"). Use
@ConfigurationProperties for
grouped properties.
23 What is Binds external configuration
@ConfigurationProperties? properties to a POJO. Type-
safe, supports validation, IDE
autocomplete with spring-boot-
configuration-processor.
24 What is Spring Profiles? Environment-specific
configuration. @Profile("prod")
activates beans for profile. Set:
[Link]=prod.
Useful for dev/staging/prod
configs.
25 What is @Scheduled in Spring? Schedules methods. Requires
@EnableScheduling. Supports:
fixedRate, fixedDelay, cron
expressions. Not distributed —
use Quartz or ShedLock for
clusters.
26 What is Spring AOP? Aspect-Oriented Programming.
Cross-cutting concerns (logging,
security, transactions) without
modifying business code.
Concepts: Aspect, JoinPoint,
Pointcut, Advice, Weaving.
27 What are Spring AOP advice @Before, @After,
# Question Answer
types? @AfterReturning,
@AfterThrowing, @Around.
@Around is most powerful —
controls method execution.
28 What is the difference between @PathVariable extracts from
@PathVariable and URL path (/users/{id}).
@RequestParam? @RequestParam from query
string (?page=0&size=10).
29 What is ResponseEntity in Wrapper for HTTP response
Spring? with status code, headers, and
body. Gives full control over
response:
[Link](body),
[Link](location
).body(body).
30 What is @RequestBody vs @RequestBody: deserializes
@ResponseBody? request body (JSON → Java).
@ResponseBody: serializes
return value to response body
(Java → JSON).
@RestController = @Controller
+ @ResponseBody.
31 What is Spring Data JPA? Abstraction over JPA.
CrudRepository, JpaRepository,
PagingAndSortingRepository.
Query by method name,
@Query, Specifications,
QueryDSL.
32 What is @Entity and @Table? @Entity marks a class as JPA
entity (maps to DB table).
@Table specifies table name.
@Column maps fields. @Id +
@GeneratedValue for primary
key.
33 What is [Link] vs LAZY: load on first access
EAGER? (default for @OneToMany).
EAGER: load with parent
(default for @ManyToOne).
Prefer LAZY, use JOIN FETCH
when needed.
34 What is JPA Criteria API? Type-safe, programmatic query
building. Alternative to string-
based JPQL. Better for dynamic
queries. Used with Specification
pattern in Spring Data.
35 What is the difference between save(): queues changes
save() and saveAndFlush() in (flushes on transaction commit).
JPA? saveAndFlush(): immediately
flushes to DB. Use
saveAndFlush() when you need
DB to reflect changes
immediately within same
# Question Answer
transaction.
36 What is Kafka and when to use Distributed event streaming
it? platform. Use when: high
throughput, event sourcing,
decoupling services, audit logs,
real-time streaming. Topics,
partitions, consumer groups,
offsets.
37 What is the difference between @RestController = @Controller
@RestController and + @ResponseBody on all
@Controller? methods. @Controller returns
view names (for
JSP/Thymeleaf).
@RestController returns
JSON/XML directly.
38 What is CORS? Cross-Origin Resource Sharing.
Browser security policy.
Configure in Spring with
@CrossOrigin,
[Link]
ppings(), or Spring Security.
39 What is SSL/TLS? HTTPS encryption. In Spring
Boot: configure in
[Link] with
[Link].* properties. In
production: terminate SSL at
load balancer/API gateway.
40 What is connection pooling? Reusing DB connections
instead of creating new ones.
HikariCP is default in Spring
Boot. Key settings:
maximumPoolSize,
minimumIdle,
connectionTimeout,
idleTimeout.
41 What is the difference between PUT: full resource replacement
PUT and PATCH? (send all fields). PATCH: partial
update (send only changed
fields). PUT is idempotent.
PATCH may not be.
42 What is optimistic vs pessimistic Optimistic: @Version field,
locking in JPA? assumes no conflict, fails on
concurrent write. Pessimistic:
DB-level lock (SELECT FOR
UPDATE), assumes conflict,
blocks reads/writes.
43 What is ACID in databases? Atomicity (all or nothing),
Consistency (valid state),
Isolation (transactions don't
interfere), Durability (committed
= persisted). ACID vs BASE in
distributed systems.
# Question Answer
44 What is database indexing? B-tree index accelerates
queries. Add on: WHERE
clause columns, JOIN columns,
ORDER BY columns, foreign
keys. Avoid over-indexing
(slows writes).
45 What is database Organizing to reduce
normalization? redundancy: 1NF (atomic
values), 2NF (no partial
dependency), 3NF (no transitive
dependency). Denormalize for
read performance.
46 What is the difference between INNER JOIN: matching rows
SQL JOIN types? only. LEFT JOIN: all from left +
matching right. RIGHT JOIN:
reverse. FULL OUTER: all rows
from both. CROSS JOIN:
cartesian product.
47 What is a deadlock in SQL? Two transactions wait for each
other's locks. Prevention:
consistent lock ordering, short
transactions, SELECT FOR
UPDATE only when needed.
48 What is Docker and how is it Containerization platform.
used with Spring Boot? Spring Boot JAR runs in Docker
container. Dockerfile: FROM
eclipse-temurin:21-jre, COPY,
ENTRYPOINT. docker-compose
for local multi-service setup.
49 What are 12-Factor App Codebase, Dependencies,
principles? Config (env vars), Backing
services, Build/release/run,
Processes, Port binding,
Concurrency, Disposability,
Dev/prod parity, Logs, Admin
processes.
50 What is observability in Three pillars: Logs (structured,
microservices? centralized — ELK/Loki),
Metrics (Micrometer +
Prometheus + Grafana), Traces
(distributed — Micrometer
Tracing + Zipkin/Jaeger).
CHAPTER 12: TRICKY & CONFUSING QUESTIONS
❓ Interview Question
What is the output of: Integer a = 127; Integer b = 127; [Link](a == b);
❓ Interview Question
What happens when you call hashCode() on a null object?
❓ Interview Question
Can you have a try block without catch?
❓ Interview Question
What is [Link]() used for?
❓ Interview Question
Why is [Link] != [Link] true?
❓ Interview Question
What is the difference between Exception and Error in Java?
❓ Interview Question
Can you make a constructor private? What is the use case?
❓ Interview Question
What is the difference between i++ and ++i in multi-threaded code?
❓ Interview Question
If @Transactional method A calls @Transactional method B in the same class, does B get
its own transaction?
@Service
public class MyService {
@Autowired private MyService self; // self-injection workaround
@Transactional
public void methodA() {
[Link](); // goes through proxy — transaction works correctly
}
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void methodB() { ... }
}
CHAPTER 13: RAPID REVISION NOTES
Use this chapter for last-minute interview preparation. Read through these key points the day before
your interview.
Spring Keywords
Topic Key Terms
Core IoC, DI, ApplicationContext, BeanFactory,
BeanLifecycle, @PostConstruct, @PreDestroy
Annotations @Component, @Service, @Repository,
@Controller, @RestController, @Configuration,
@Bean
Transaction @Transactional, propagation, isolation,
rollbackFor, self-invocation, AOP proxy
JPA EntityManager, PersistenceContext, dirty
checking, N+1, JOIN FETCH, @EntityGraph, lazy
loading
Security JWT, stateless, SecurityFilterChain,
@PreAuthorize, RBAC, CORS, CSRF
Boot auto-configuration, @ConditionalOn*,
[Link], @SpringBootApplication, profiles
Cache @Cacheable, @CacheEvict, @CachePut, TTL,
LRU, Redis, cache-aside
Architecture Keywords
Topic Key Terms
REST stateless, idempotent, safe, HATEOAS,
versioning, pagination, rate limiting, idempotency
key
Microservices API Gateway, Service Discovery, Circuit Breaker,
Saga, CQRS, Event Sourcing, Bulkhead
Messaging topic, partition, consumer group, offset, at-least-
once, exactly-once, DLQ (Dead Letter Queue)
Observability Logs (ELK), Metrics (Prometheus/Grafana),
Traces (Zipkin/Jaeger), Micrometer
DB ACID, index, N+1, optimistic/pessimistic locking,
connection pool, migration, normalization
Performance caching, async, pagination, read replica, CQRS,
connection pooling, CDN