Complete Java & Spring Boot Interview Guide 2025
Complete Java & Spring Boot Interview Guide 2025
Guide 2025
Comprehensive preparation for Java 8-21, Spring Boot 3.5.6, System Design, Algorithms & DevOps
Java 8-21 Spring Boot 3.5.6 Spring 6 Microservices System Design Database & SQL Algorithms
DevOps
📚 Table of Contents
1
Core Java (Java 8-21)
Answer: Encapsulation, Inheritance, Polymorphism, and Abstraction. They promote code reusability and
modularity.
Answer: HashMap is not thread-safe, while ConcurrentHashMap allows concurrent read/write operations by
segmenting data and prevents ConcurrentModificationException.
Null Keys/Values ✅ Allows one null key, multiple null values ❌ Does not allow null keys or values
Fail-fast (throws
Iterator Behavior Weakly consistent
ConcurrentModificationException)
Answer: Stream API processes collections in a functional way (filter, map, reduce). It improves readability and
supports parallel processing.
import java.util.*;
import java.util.stream.*;
// Example 4: Grouping by
Map> grouped = names.stream()
.collect(Collectors.groupingBy(String::length));
}
}
4 Explain the difference between final, finally, and finalize().
Answer:
final: Makes a variable constant or prevents inheritance/method overriding
finally: Block that executes after try-catch, always runs (except System.exit())
finalize(): Called by GC before object destruction (deprecated in Java 9)
Answer: Introduced in Java 14, records are compact classes for immutable data carriers.
// Custom method
public String displayInfo() {
return name + " (" + age + ") - " + email;
}
}
// Usage
User user = new User("John Doe", "[email protected]", 30);
System.out.println(user.name()); // Accessor method
System.out.println(user.toString()); // Auto-generated toString()
6 What are sealed classes?
@Override
public double area() {
return Math.PI * radius * radius;
}
}
@Override
public double area() {
return width * height;
}
}
7 What are virtual threads?
Answer: Introduced in Java 21 — lightweight threads that scale concurrency efficiently without blocking OS
threads.
import java.util.concurrent.*;
import java.util.stream.*;
virtualThread.join();
}
}
2
Spring Boot 3.5.6 & Spring 6
package com.example.api.controller;
import jakarta.validation.Valid;
import jakarta.validation.constraints.*;
import org.springframework.http.*;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/v1/users")
@Validated
public class UserController {
@PostMapping
public ResponseEntity createUser(
@Valid @RequestBody CreateUserRequest request) {
UserResponse response = userService.createUser(request);
return ResponseEntity
.created(URI.create("/api/v1/users/" + response.id()))
.body(response);
}
@GetMapping("/{id}")
public ResponseEntity getUser(
@PathVariable @Min(1) Long id) {
return userService.findById(id)
.map(user -> ResponseEntity.ok(mapToResponse(user)))
.orElseThrow(() -> new ResourceNotFoundException(
"User not found with id: " + id));
}
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity handleValidationException(
MethodArgumentNotValidException ex) {
return ResponseEntity.badRequest()
.body(new ErrorResponse("Validation failed", errors));
}
}
}
@Pattern(
regexp = "^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).{8,}$",
message = "Password must contain 8+ chars with uppercase, lowercase, and digit"
)
String password
) {}
19 Implement a custom HealthIndicator for Spring Boot Actuator
package com.example.health;
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.stereotype.Component;
@Component
public class DatabaseHealthIndicator implements HealthIndicator {
@Override
public Health health() {
try {
// Check database connection
Integer result = jdbcTemplate.queryForObject(
"SELECT 1", Integer.class);
package com.example.repository;
import org.springframework.data.jpa.repository.*;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
@Repository
public interface UserRepository extends JpaRepository {
if (criteria.getEmail() != null) {
predicates.add(cb.like(root.get("email"),
"%" + criteria.getEmail() + "%"));
}
if (criteria.getMinAge() != null) {
predicates.add(cb.ge(root.get("age"),
criteria.getMinAge()));
}
if (criteria.getRole() != null) {
Join roles = root.join("roles");
predicates.add(cb.equal(roles.get("name"),
criteria.getRole()));
}
// Projection interface
public interface UserOrderProjection {
Long getUserId();
String getEmail();
Long getOrderCount();
}
21 Configure Spring Security 6 with JWT authentication
Spring Security 6 Configuration
package com.example.security.config;
import org.springframework.context.annotation.*;
import org.springframework.security.config.annotation.method.configuration.*;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.*;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
@Configuration
@EnableWebSecurity
@EnableMethodSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.csrf(csrf -> csrf.disable())
.authorizeHttpRequests(authz -> authz
.requestMatchers("/api/auth/**").permitAll()
.requestMatchers("/api/public/**").permitAll()
.requestMatchers("/swagger-ui/**", "/v3/api-docs/**").permitAll()
.requestMatchers("/api/admin/**").hasRole("ADMIN")
.requestMatchers("/api/user/**").hasAnyRole("USER", "ADMIN")
.anyRequest().authenticated()
)
.sessionManagement(session ->
session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
)
.addFilterBefore(jwtAuthenticationFilter(),
UsernamePasswordAuthenticationFilter.class)
.exceptionHandling(exceptions ->
exceptions.authenticationEntryPoint(jwtAuthenticationEntryPoint())
);
return http.build();
}
@Bean
public JwtAuthenticationFilter jwtAuthenticationFilter() {
return new JwtAuthenticationFilter();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response,
FilterChain filterChain)
throws ServletException, IOException {
authentication.setDetails(
new WebAuthenticationDetailsSource().buildDetails(request)
);
SecurityContextHolder.getContext().setAuthentication(authentication);
}
filterChain.doFilter(request, response);
}
3
System Design & Architecture
Use Case: Database connections, logging, Use Case: Payment processors, notification services,
configuration management document converters
Thread-Safe Singleton Factory Pattern Example
return instance;
}
}
Use Case: Event notifications, stock market updates, Use Case: Sorting algorithms, compression methods,
chat applications payment gateways
Observer Pattern Example Strategy Pattern Example
SD1 Design a URL Shortening Service (TinyURL)
📊 System Requirements:
Functional: Shorten URLs, redirect to original URLs, custom URLs, analytics
Non-Functional: High availability (99.99%), low latency (< 100ms), scalability
Scale: 100M URLs, 100M requests/day, 1KB per URL record
🏗️ Architecture Components:
1. API Layer: REST APIs for URL operations
2. Encoding Service: Base62 encoding for short URLs
3. Storage: Redis (cache) + PostgreSQL (persistent)
4. CDN: For static assets and frequently accessed URLs
5. Load Balancer: Distribute traffic across servers
6. Analytics: Track clicks, referrers, geographical data
return shortURL.reverse().toString();
}
Answer: Lazy: Loads data when accessed. Eager: Loads immediately with parent entity.
Performance Better for infrequently accessed data Better for frequently accessed data
N+1 Problem Can cause N+1 queries Single query with joins
Memory Usage Lower (loads only needed data) Higher (loads all related data)
Use Case Large collections, infrequent access Small collections, always needed
@Entity
public class Order {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Entity
public class User {
@Id
@GeneratedValue
private Long id;
@Entity
public class Order {
@Id
@GeneratedValue
private Long id;
Answer: save(): Persists data in session. saveAndFlush(): Persists and immediately writes changes to DB.
@Service
@Transactional
public class UserService {
@Autowired
private UserRepository userRepository;
return savedUser;
}
return freshUser;
}
}
5
Microservices with Spring Cloud
68 What is a microservice?
Answer: Independent, small, loosely coupled service focusing on a specific business capability.
🏗️ Microservices Characteristics:
Single Responsibility: Each service handles one business capability
Independent Deployment: Can be deployed independently
Technology Diversity: Can use different tech stacks
Decentralized Data Management: Each service owns its database
Fault Isolation: Failure in one service doesn't affect others
Microservices Architecture Example
// Order Controller
@RestController
@RequestMapping("/api/orders")
public class OrderController {
@Autowired
private InventoryServiceClient inventoryService;
@PostMapping
public ResponseEntity createOrder(@RequestBody OrderRequest request) {
// Check inventory using Feign client
InventoryResponse inventory = inventoryService.checkInventory(
request.getProductId(), request.getQuantity());
if (!inventory.isAvailable()) {
throw new InsufficientInventoryException("Not enough stock");
}
return ResponseEntity.ok(order);
}
}
@PostMapping("/api/inventory/check")
InventoryResponse checkInventory(
@RequestParam("productId") Long productId,
@RequestParam("quantity") Integer quantity);
}
Answer: REST APIs, Feign clients, gRPC, or message brokers (Kafka, RabbitMQ).
@Bean
public KafkaTemplate kafkaTemplate() {
return new KafkaTemplate<>(producerFactory());
}
}
@Component
public class OrderEventPublisher {
@Autowired
private KafkaTemplate kafkaTemplate;
// 3. gRPC Communication
@GrpcClient("product-service")
private ProductServiceGrpc.ProductServiceBlockingStub productStub;
77 What is Docker?
Answer: A containerization platform that packages apps with dependencies for consistent deployment.
WORKDIR /app
# Download dependencies
RUN ./mvnw dependency:go-offline -B
# Build application
RUN ./mvnw clean package -DskipTests
# Runtime stage
FROM eclipse-temurin:17-jre-alpine
WORKDIR /app
# Expose port
EXPOSE 8080
# Run application
ENTRYPOINT ["java", "-jar", "/app.jar"]
services:
postgres:
image: postgres:15-alpine
environment:
POSTGRES_DB: mydb
POSTGRES_USER: admin
POSTGRES_PASSWORD: secret
volumes:
- postgres_data:/var/lib/postgresql/data
ports:
- "5432:5432"
networks:
- app-network
redis:
image: redis:7-alpine
ports:
- "6379:6379"
networks:
- app-network
app:
build: .
ports:
- "8080:8080"
environment:
SPRING_DATASOURCE_URL: jdbc:postgresql://postgres:5432/mydb
SPRING_DATASOURCE_USERNAME: admin
SPRING_DATASOURCE_PASSWORD: secret
SPRING_REDIS_HOST: redis
depends_on:
- postgres
- redis
networks:
- app-network
networks:
app-network:
driver: bridge
volumes:
postgres_data:
Answer: Continuous Integration & Continuous Deployment automate testing and deployment pipelines.
# .github/workflows/ci-cd.yml
name: CI/CD Pipeline
on:
push:
branches: [ main, develop ]
pull_request:
branches: [ main ]
jobs:
test:
runs-on: ubuntu-latest
services:
postgres:
image: postgres:15-alpine
env:
POSTGRES_PASSWORD: postgres
options: >-
--health-cmd pg_isready
--health-interval 10s
--health-timeout 5s
--health-retries 5
ports:
- 5432:5432
redis:
image: redis:7-alpine
options: >-
--health-cmd "redis-cli ping"
--health-interval 10s
--health-timeout 5s
--health-retries 5
ports:
- 6379:6379
steps:
- uses: actions/checkout@v3
build-and-push:
runs-on: ubuntu-latest
needs: test
if: github.ref == 'refs/heads/main'
steps:
- uses: actions/checkout@v3
deploy:
runs-on: ubuntu-latest
needs: build-and-push
if: github.ref == 'refs/heads/main'
steps:
- name: Deploy to Kubernetes
uses: azure/k8s-deploy@v4
with:
namespace: production
manifests: |
k8s/deployment.yaml
k8s/service.yaml
k8s/ingress.yaml
images: |
${{ secrets.DOCKER_USERNAME }}/myapp:${{ github.sha }}
📊 Document Summary
97+ 50+ 10 5
Interview Questions Code Examples Design Patterns System Designs
This document contains the complete Java & Spring Boot interview preparation guide with all questions, answers,
and code examples. Save this HTML file for offline reference.
Java 21 Spring Boot 3.5.6 System Design Microservices SQL & NoSQL Algorithms
📚 Contents
1
Core Java (8-21) 2. Core Java (Java 8-21)
Spring Boot 3.5.6
🏗️ OOP Principles:
System Design
Encapsulation: Binding data and methods together, hiding internal state
Testing Inheritance: Creating new classes from existing ones
Polymorphism: Ability to take many forms (method
Algorithms overriding/overloading)
Abstraction: Hiding complex implementation details
HR & Behavioral
Extra Q&A
🏷️ Quick Links
Code Examples
Design Patterns
Performance
Security
Scalability
2.2. 2 Difference between HashMap and ConcurrentHashMap?
Answer:
private ThreadSafeSingleton() {
// Prevent reflection attacks
if (instance != null) {
throw new IllegalStateException("Singleton already initia
}
}
💡 Explanation:
Double-checked locking ensures thread safety while minimizing
synchronization overhead. The volatile keyword prevents instruction
reordering issues.
Enum singleton is the most recommended approach as it's inherently
thread-safe, serialization-safe, and reflection-safe.
2
4. Spring Boot 3.5.6 & Spring 6
import jakarta.validation.Valid;
import jakarta.validation.constraints.*;
import org.springframework.http.*;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/v1/users")
@Validated
public class UserController {
@PostMapping
public ResponseEntity<UserResponse> createUser(
@Valid @RequestBody CreateUserRequest request) {
// Business logic here
UserResponse response = userService.createUser(request);
return ResponseEntity
.created(URI.create("/api/v1/users/" + response.id()))
.body(response);
}
@GetMapping("/{id}")
public ResponseEntity<UserResponse> getUser(
@PathVariable @Min(1) Long id) {
return userService.findById(id)
.map(user -> ResponseEntity.ok(mapToResponse(user)))
.orElseThrow(() -> new ResourceNotFoundException("User no
}
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<ErrorResponse> handleValidationExceptio
MethodArgumentNotValidException ex) {
return ResponseEntity.badRequest()
.body(new ErrorResponse("Validation failed", errors))
}
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<ErrorResponse> handleNotFoundException(
ResourceNotFoundException ex) {
return ResponseEntity.status(HttpStatus.NOT_FOUND)
.body(new ErrorResponse(ex.getMessage()));
}
}
}
@Pattern(
regexp = "^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=])(
message = "Password must contain at least 8 characters, one u
)
String password
) {}
import org.springframework.context.annotation.*;
import org.springframework.security.config.annotation.method.configur
import org.springframework.security.config.annotation.web.builders.Ht
import org.springframework.security.config.annotation.web.configurati
import org.springframework.security.config.http.SessionCreationPolicy
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncod
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswo
@Configuration
@EnableWebSecurity
@EnableMethodSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http)
http
.csrf(csrf -> csrf.disable())
.authorizeHttpRequests(authz -> authz
.requestMatchers("/api/auth/**").permitAll()
.requestMatchers("/api/public/**").permitAll()
.requestMatchers("/swagger-ui/**", "/v3/api-docs/**")
.requestMatchers("/api/admin/**").hasRole("ADMIN")
.requestMatchers("/api/user/**").hasAnyRole("USER", "
.anyRequest().authenticated()
)
.sessionManagement(session ->
session.sessionCreationPolicy(SessionCreationPolicy.S
)
.addFilterBefore(jwtAuthenticationFilter(),
UsernamePasswordAuthenticationFilter.class)
.exceptionHandling(exceptions ->
exceptions.authenticationEntryPoint(jwtAuthentication
);
return http.build();
}
@Bean
public JwtAuthenticationFilter jwtAuthenticationFilter() {
return new JwtAuthenticationFilter();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response,
FilterChain filterChain)
throws ServletException, IOException {
UsernamePasswordAuthenticationToken authentication =
new UsernamePasswordAuthenticationToken(
userDetails, null, userDetails.getAuthorities
authentication.setDetails(
new WebAuthenticationDetailsSource().buildDetails
);
SecurityContextHolder.getContext().setAuthentication(
}
filterChain.doFilter(request, response);
}
3
6. System Design & Architecture
Monolithic Microservices
🏢 🔗
Architecture Architecture
Advantages: Advantages:
Disadvantages:
Single point of failure Distributed system
Difficult to scale horizontally complexity
Long deployment cycles Eventual consistency
Technology lock-in Operational overhead
Network latency
Event-Driven Serverless
⚡ ☁️
Architecture Architecture
No Ops
When to use: Real-time processing,
IoT, financial systems, notification
When to use: Sporadic workloads,
systems.
event processing, API backends,
chatbots.
Advantages:
Disadvantages:
Answer:
📊 Requirements:
Functional: Shorten URLs, redirect to original URLs, custom URLs
Non-Functional: High availability, scalability, low latency
Scale: 100M URLs, 100M requests/day, 1KB per URL
🏗️ Architecture:
1. API Layer: REST APIs for URL shortening and redirection
2. Encoding Service: Base62 encoding for short URLs
3. Storage: Redis (cache) + PostgreSQL (persistent storage)
4. Cache Strategy: LRU cache for hot URLs
5. CDN: For static assets and frequently accessed URLs
return shortURL.reverse().toString();
}
return id;
}
6.2.SD2 Design a Distributed Cache System
Answer:
🔑 Requirements:
Capacity: 1TB total, distributed across nodes
Latency: < 5ms for cache hits
Consistency: Eventual consistency
Availability: 99.99%
🏗️ Architecture Components:
1. Consistent Hashing: For data distribution and minimal reshuffling
2. Replication: Each key stored in N nodes (typically 3)
3. LRU Eviction: When cache reaches capacity
4. Write-through/Write-behind: Cache persistence strategies
5. Health Checks: Automatic node failure detection and recovery
return circle.get(nodeHash);
}
+
8. Extra Interview Questions & Answers
@Component
public class OrderSagaOrchestrator {
@Transactional
public void processOrder(OrderRequest request) {
try {
// Step 1: Reserve inventory
inventoryService.reserveItems(request.getItems());
} catch (Exception e) {
// Compensating transactions
inventoryService.releaseReservation(request.getItems());
paymentService.refundPayment(request.getPayment());
throw e;
}
}
}
@EventListener
@TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT
public void handleOrderCreated(OrderCreatedEvent event) {
// Publish events for other services
eventPublisher.publish(new ReserveInventoryEvent(event.getOrd
}
@EventListener
public void handleInventoryReserved(InventoryReservedEvent event)
eventPublisher.publish(new ProcessPaymentEvent(event.getOrder
}
@EventListener
public void handlePaymentProcessed(PaymentProcessedEvent event) {
if (event.isSuccess()) {
eventPublisher.publish(new CompleteOrderEvent(event.getOr
} else {
eventPublisher.publish(new CancelOrderEvent(event.getOrde
}
}
}
8.2. E2 How to implement rate limiting in Spring Boot?
@Configuration
public class RateLimitConfig {
@Bean
public RateLimiterRegistry rateLimiterRegistry() {
return RateLimiterRegistry.of(
RateLimiterConfig.custom()
.limitForPeriod(100) // 100 requests
.limitRefreshPeriod(Duration.ofSeconds(60)) // per mi
.timeoutDuration(Duration.ofMillis(500)) // wait t
.build()
);
}
@Bean
public RateLimiterProperties rateLimiterProperties() {
return new RateLimiterProperties();
}
}
@Service
public class ApiService {
if (current == 1) {
// Set expiry on first request
redisTemplate.expire(redisKey, duration.getSeconds(), Tim
}
Answer:
🛡️ Security Checklist:
1. Input Validation: Validate all inputs, use DTO validation
2. Authentication: JWT with proper expiration, refresh tokens
3. Authorization: Role-based access control (RBAC)
4. HTTPS: Enforce HTTPS, use HSTS headers
5. SQL Injection: Use prepared statements, JPA named parameters
6. XSS Protection: Content Security Policy, input sanitization
7. CSRF Protection: Enable CSRF for state-changing operations
8. Secrets Management: Use environment variables, vaults
9. Audit Logging: Log security events
10. Regular Updates: Keep dependencies updated
@Configuration
@EnableWebSecurity
public class AdvancedSecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws
http
// HTTPS enforcement
.requiresChannel(channel ->
channel.anyRequest().requiresSecure())
// Headers security
.headers(headers -> headers
.contentSecurityPolicy(csp -> csp
.policyDirectives("default-src 'self'; script-src
.httpStrictTransportSecurity(hsts -> hsts
.includeSubDomains(true)
.maxAgeInSeconds(31536000))
.frameOptions(frame -> frame.sameOrigin())
.xssProtection(xss -> xss.enable()))
// CORS configuration
.cors(cors -> cors.configurationSource(corsConfigurationS
// Session management
.sessionManagement(session -> session
.sessionCreationPolicy(SessionCreationPolicy.STATELES
.maximumSessions(1))
// Authentication
.oauth2ResourceServer(oauth2 -> oauth2
.jwt(jwt -> jwt.jwtAuthenticationConverter(jwtAuthent
// Authorization
.authorizeHttpRequests(authz -> authz
.requestMatchers("/api/admin/**").hasRole("ADMIN")
.requestMatchers("/api/user/**").hasAnyRole("USER", "
.requestMatchers("/api/public/**").permitAll()
.anyRequest().authenticated());
return http.build();
}
10.1.
A1 Implement Trie data structure for autocomplete
public TrieNode() {
this.children = new HashMap<>();
this.isEndOfWord = false;
this.frequency = 0;
}
}
public Trie() {
this.root = new TrieNode();
}
current.setEndOfWord(true);
current.setFrequency(current.getFrequency() + 1);
current.setWord(word);
}
return results.stream()
.limit(limit)
.map(wf -> wf.word)
.collect(Collectors.toList());
}
return current;
}
return results.stream()
.map(wf -> wf.word)
.collect(Collectors.toList());
}
class WordFrequency {
String word;
int frequency;
import java.util.*;
if (node != null) {
// Update existing node
node.value = value;
moveToFront(node);
} else {
// Create new node
node = new Node(key, value);
cache.put(key, node);
addToFront(node);
// Check capacity
if (cache.size() > capacity) {
removeLRU();
}
}
}
12.1.
P1 How to optimize Spring Boot application performance?
🎯 Optimization Strategies:
jpa:
properties:
hibernate:
jdbc:
batch_size: 50
order_inserts: true
order_updates: true
generate_statistics: true
cache:
type: redis
redis:
time-to-live: 600000
cache-null-values: false
management:
endpoints:
web:
exposure:
include: health,metrics,prometheus
metrics:
export:
prometheus:
enabled: true
distribution:
percentiles-histogram:
http.server.requests: true
# JVM Options for production
# -Xms2g -Xmx2g -XX:+UseG1GC -XX:MaxGCPauseMillis=200
# -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/tmp
# -XX:NativeMemoryTracking=summary -XX:+PrintGCDetails
🔧 Key Optimizations:
1. Connection Pooling: Use HikariCP with proper pool sizing
2. Batch Processing: Enable JDBC batching for bulk operations
3. Caching Strategy: Multi-level caching (L1/L2/Redis)
4. Async Processing: Use @Async for non-blocking operations
5. Database Indexing: Create indexes on frequently queried columns
6. Garbage Collection: Use G1GC for better throughput
This comprehensive guide covers everything from Core Java 8-21 to advanced
System Design patterns.
Continuously updated for 2025 interviews with latest Spring Boot 3.5.6 features.
14.1.
What are the main OOP principles in Java?
Encapsulation, Inheritance, Polymorphism, and Abstraction. They promote code reusability and modularity.
14.2.
Difference between HashMap and ConcurrentHashMap?
HashMap is not thread-safe, while ConcurrentHashMap allows concurrent read/write operations by segmenting data and
prevents ConcurrentModificationException.
14.3.
What is the Stream API used for?
Stream API processes collections in a functional way (filter, map, reduce). It improves readability and supports parallel
processing.
14.4.
Explain the difference between final, finally, and finalize().
14.5.
What are records in Java?
Introduced in Java 14, records are compact classes for immutable data carriers.
14.6.
What are sealed classes?
14.7.
What are virtual threads?
Introduced in Java 21 — lightweight threads that scale concurrency efficiently without blocking OS threads.
16. Spring Core & Boot Basics
16.1.
What is Dependency Injection (DI)?
A design pattern where Spring manages object creation and wiring instead of manually instantiating dependencies.
16.2.
Difference between @Component, @Service, and @Repository?
16.3.
What is the role of @SpringBootApplication?
16.4.
How does Spring Boot simplify configuration?
16.5.
How do you handle exceptions globally in Spring Boot?
16.6.
What is the difference between application.properties and application.yml?
Both define configurations; .yml supports hierarchical data structure and is easier to read.
18. Spring Boot Advanced
18.1.
What is @Transactional used for?
Eliminates boilerplate DAO code and provides CRUD methods using repository interfaces.
18.3.
What is the purpose of @Cacheable annotation?
18.4.
How can you schedule tasks in Spring Boot?
18.6.
How do you secure REST APIs with JWT?
Client logs in → receives JWT → server validates token for access control.
18.7.
How do you create a Docker image for a Spring Boot app?
1. Create Dockerfile:
FROM openjdk:17
COPY target/app.jar app.jar
ENTRYPOINT ['java', '-jar', '/app.jar']
20.1.
Explain lazy vs eager fetching.
20.2.
What are the common entity relationships?
20.4.
How does Hibernate handle caching?
22.1.
What is a microservice?
22.2.
How do microservices communicate?
22.3.
What is a Config Server?
22.4.
What is the role of Eureka Server?
Service discovery — helps services find and communicate with each other dynamically.
22.5.
What is Circuit Breaker in microservices?
22.6.
What is an API Gateway?
Single entry point for client requests that handles routing, security, and rate-limiting.
22.7.
What is idempotent API?
An API that can be called multiple times without changing the result (e.g., PUT or GET).
24. Deployment, Docker & DevOps Basics
24.1.
What is Docker?
A containerization platform that packages apps with dependencies for consistent deployment.
24.2.
Difference between Docker image and container?
24.4.
How do you store application secrets safely?
24.5.
What is CI/CD?
Continuous Integration & Continuous Deployment automate testing and deployment pipelines.
26.1.
What is a layered architecture in Spring Boot?
26.2.
Which design patterns are commonly used in Spring?
26.3.
What are REST API best practices?
26.5.
How does caching improve performance?
28.1.
What is the difference between unit and integration testing?
28.2.
How do you test a service using Mockito?
28.3.
What is @SpringBootTest used for?
28.4.
What are Testcontainers?
Library that runs real dependencies (like DBs) in Docker during tests.
30.1.
Tell me about your last project.
Explain business goal, tech stack (Spring Boot, Angular, MySQL, Docker), and your role.
30.2.
What challenges did you face and how did you solve them?
Discuss a real issue like slow queries or security setup and your solution.
30.3.
How do you stay updated with new tech?
30.4.
How do you ensure code quality?
Code reviews, SonarQube checks, unit tests, and following clean code principles.