Java Interview Question and Preparation
Java Interview Question and Preparation
Core Java
1. Java 8 Features
Interviewer Expecta on: The candidate should list key Java 8 features, explain their purpose, and
provide examples demonstra ng their use. They should highlight how these features improve code
quality or performance.
Answer: Java 8 (released March 2014) introduced transforma ve features to improve produc vity,
readability, and performance. Key features include:
Stream API: Provides a declara ve way to process collec ons, suppor ng opera ons like
filter, map, and reduce.
Func onal Interfaces: Interfaces with a single abstract method (e.g., Runnable, Comparator),
used with lambdas.
Default and Sta c Methods in Interfaces: Allow adding methods to interfaces without
breaking implementa ons.
Date and Time API: A modern replacement for java.u l.Date, using LocalDate, LocalTime,
etc.
o Example: LocalDate.now().plusDays(1);
Nashorn JavaScript Engine: Executes JavaScript within Java (though deprecated in later
versions).
What to Highlight:
Prac cal use cases (e.g., Stream API for data processing).
How features like lambdas reduce boilerplate code.
2. Stream API
Interviewer Expecta on: The candidate should explain the Stream API’s purpose, opera ons, and
performance considera ons, with examples showing sequen al and parallel streams.
Answer: The Stream API enables func onal-style processing of collec ons, emphasizing declara ve
code over impera ve loops. Streams operate on a data source (e.g., List, Set) and support opera ons
like filtering, mapping, and reducing.
Key Components:
o Intermediate Opera ons: Lazy opera ons like filter(), map(), sorted().
o Terminal Opera ons: Eager opera ons like collect(), forEach(), reduce().
Example:
java
System.out.println(doubledEvens); // [4, 8]
Parallel Streams:
o Example: numbers.parallelStream().forEach(System.out::println);
Performance:
o Streams are not always faster than loops; overhead exists for small datasets.
o Parallel streams shine for large datasets but require careful tuning to avoid
conten on.
What to Highlight:
Lazy evalua on (intermediate opera ons don’t execute un l a terminal opera on is called).
Common pi alls (e.g., modifying the source during stream processing).
Interviewer Expecta on: The candidate should define lambda expressions, explain their syntax, and
demonstrate their use with func onal interfaces, including custom ones.
Answer: Lambda Expressions are anonymous func ons introduced in Java 8, enabling concise code
for implemen ng func onal interfaces.
Func onal Interface: An interface with exactly one abstract method, marked with
@Func onalInterface.
o Example:
@Func onalInterface
interface MathOp {
System.out.println(add.operate(5, 3)); // 8
Use Cases:
Benefits:
What to Highlight:
How lambdas work with built-in func onal interfaces like java.u l.func on.*.
Interviewer Expecta on: The candidate should explain Java’s threading model, synchroniza on
techniques, and lock strategies, with examples of synchronized, ReentrantLock, and concurrent
u li es.
Answer: Java’s mul threading allows concurrent execu on of tasks using threads, managed by the
JVM.
executor.shutdown();
Synchroniza on:
Example:
counter++;
Example:
void increment() {
lock.lock();
try {
counter++;
} finally {
lock.unlock();
}
Concurrent U li es (java.u l.concurrent):
Lock Strategies:
o Op mis c Locking: Assumes conflicts are rare, using version checks (e.g., JPA
@Version).
o Pessimis c Locking: Locks resources to prevent conflicts (e.g., database row locks).
What to Highlight:
5. String Class
Interviewer Expecta on: The candidate should explain the String class’s immutability, string pool,
and common methods, addressing performance considera ons.
Answer: The String class in Java is immutable, final, and widely used for text manipula on.
Immutability:
String Pool:
Common Methods:
Performance:
sb.append(i);
What to Highlight:
Interviewer Expecta on: The candidate should explain the sta c keyword’s role in variables,
methods, blocks, and nested classes, with examples.
Answer: The sta c keyword indicates that a member belongs to the class, not instances.
Sta c Variables:
Sta c Methods:
Sta c Blocks:
o Example:
java
sta c {
o Example:
java
class Outer {
What to Highlight:
Memory implica ons (sta c fields persist for the class’s life me).
Interviewer Expecta on: The candidate should clarify the difference between global (sta c) and
instance variables, their scope, and lifecycle.
Answer:
Instance Variables:
Comparison:
o Example:
class User {
User(String name) {
this.name = name;
totalUsers++;
What to Highlight:
Interviewer Expecta on: The candidate should explain the Java Memory Model (JMM), memory
areas, and thread interac ons, with a focus on visibility and synchroniza on.
Answer: The Java Memory Model defines how threads interact with memory, ensuring consistent
behavior.
Memory Areas:
o Program Counter (PC) Register: Tracks the current instruc on per thread.
JMM Guarantees:
o Visibility: Changes by one thread may not be immediately visible to others unless
synchronized.
Key Concepts:
What to Highlight:
Real-world issues like race condi ons and how JMM mi gates them.
Interviewer Expecta on: The candidate should describe the Java Collec ons Framework, focus on
HashMap, synchroniza on op ons, and using model classes as keys.
Answer: The Java Collec ons Framework provides data structures for storing and manipula ng
objects.
HashMap:
Synchronized HashMap:
o Example:
class User {
String id;
@Override
return id.equals(user.id);
@Override
return id.hashCode();
o Pi alls: Mutable keys can break map integrity if modified a er inser on.
What to Highlight:
Interviewer Expecta on: The candidate should explain common design pa erns, their purposes, and
provide Java implementa ons, with emphasis on real-world use.
Answer: Design pa erns are reusable solu ons to common so ware problems. Key pa erns include:
Singleton:
o Example:
private Singleton() {}
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
return instance;
Factory:
o Example:
class ShapeFactory {
return null;
Observer:
o Example:
class Subject {
Other Pa erns:
What to Highlight:
Interviewer Expecta on: The candidate should define each SOLID principle, explain its importance,
and provide examples demonstra ng adherence or viola on.
Answer: SOLID principles guide object-oriented design to create maintainable, scalable code:
o Example: Separate UserService (handles user data) from EmailService (sends emails).
O - Open/Closed Principle:
o Example:
o Example: A Bird interface with fly() should not be implemented by Ostrich (which
can’t fly).
o Example:
class Service {
What to Highlight:
Interviewer Expecta on: The candidate should discuss Java version adop on, key features beyond
Java 8, and how Java 8 differs from prior versions.
Answer:
o Java 11: Long-term support (LTS), common in enterprises for its balance of features
and stability.
o Java 17: Latest LTS, gaining trac on for records, sealed classes, and performance
improvements.
o Java 21: Newer LTS, includes virtual threads (Project Loom) and pa ern matching.
o Introduced lambdas, Stream API, Op onal, default methods, and new Date/Time
API.
o Example: Java 7 required verbose anonymous classes; Java 8 uses lambdas:
// Java 7
};
// Java 8
Post-Java 8 Features:
o Java 21: Virtual threads, structured concurrency, pa ern matching for switch.
What to Highlight:
13. Abstract Class and Func onal Interfaces (Example-Based Ques ons)
Interviewer Expecta on: The candidate should compare abstract classes and func onal interfaces,
provide examples, and explain when to use each.
Answer:
Abstract Class:
o Can have abstract and concrete methods, state (fields), and constructors.
o Example:
String name;
Animal(String name) { this.name = name; }
o Example:
@Func onalInterface
interface SoundMaker {
void makeSound();
Comparison:
o Func onal Interface: Use for single behaviors, especially with Streams/lambdas.
What to Highlight:
Limita ons (e.g., single inheritance vs. mul ple interface implementa on).
Interviewer Expecta on: The candidate should explain excep on handling mechanics, finally
behavior, and edge cases like suppressed excep ons.
try {
int result = 10 / 0;
} finally {
System.out.println("Cleanup");
Key Points:
o Catch: Handles specific excep on types; can have mul ple catches.
o Finally: Executes regardless of excep on, ideal for cleanup (e.g., closing resources).
Example:
fis.read();
} catch (IOExcep on e) {
e.printStackTrace();
Edge Cases:
o Suppressed Excep ons: In try-with-resources, if both try block and close throw
excep ons, the close excep on is suppressed.
Example:
try {
return 1;
} finally {
return 2; // 2 is returned
What to Highlight:
Interviewer Expecta on: The candidate should explain the main method’s role, signature varia ons,
and related nuances.
Answer: The main method is the entry point for Java applica ons.
Standard Signature:
System.out.println("Hello, World!");
Varia ons:
Nuances:
o Can be in any class; JVM looks for it based on the executed class.
System.out.println(arg);
What to Highlight:
Use in CLI applica ons vs. frameworks (e.g., Spring Boot’s embedded main).
Interviewer Expecta on: The candidate should explain Java’s operator precedence, provide
examples, and discuss how parentheses clarify intent.
o Addi ve: +, -
o Equality: ==, !=
o Bitwise: &, ^, |
o Logical: &&, ||
o Ternary: ?:
Example:
int x = 2 + 3 * 4; // 14 (* before +)
o Example: if ((a > b) && (c < d)) is clearer than if (a > b && c < d).
What to Highlight:
Interviewer Expecta on: The candidate should explain constructor chaining within a class and across
inheritance, with examples.
Answer: Constructor chaining refers to one constructor calling another to reuse ini aliza on logic.
Within a Class:
o Example:
class Person {
String name;
int age;
Person(String name) {
this.name = name;
this.age = age;
Across Inheritance:
o Example:
class Animal {
String species;
Animal(String species) {
this.species = species;
String name;
this.name = name;
Rules:
o If a parent class lacks a no-arg constructor, subclasses must explicitly call super().
What to Highlight:
Databases
1. Basic Concepts
Interviewer Expecta on: The candidate should explain core database concepts like tables, keys, and
ACID proper es, with prac cal insights.
Answer:
Keys:
Indexes:
What to Highlight:
Trade-offs of indexing.
2. Normaliza on
Interviewer Expecta on: The candidate should define normaliza on, explain normal forms, and
discuss when to denormalize.
Answer: Normaliza on organizes a database to reduce redundancy and ensure data integrity.
Normal Forms:
Denormaliza on:
o Inten onally violates normaliza on for performance (e.g., caching aggregated data).
Trade-offs:
What to Highlight:
Interviewer Expecta on: The candidate should write SQL queries for aggrega ons, sor ng, grouping,
and advanced clauses, explaining their purpose.
Answer:
Order By:
Group By:
Clauses:
o Ranking:
Example:
SELECT name, salary,
FROM employees;
What to Highlight:
4. Connec on Pool
Interviewer Expecta on: The candidate should explain connec on pooling, its benefits, and
configura on in Java applica ons.
Answer: A connec on pool manages a cache of database connec ons to improve performance.
How It Works:
Configura on in Java:
yaml
spring:
datasource:
hikari:
maximum-pool-size: 10
minimum-idle: 5
o Programma c Example:
config.setJdbcUrl("jdbc:mysql://localhost:3306/db");
config.setUsername("user");
config.setPassword("pass");
config.setMaximumPoolSize(10);
Key Se ngs:
Benefits:
What to Highlight:
Interviewer Expecta on: The candidate should discuss general and Spring Boot-specific techniques
to op mize database performance.
Answer:
General Techniques:
Use @Query for custom queries instead of JPQL for complex cases.
o Batch Inserts:
Example:
@Transac onal
userRepository.saveAll(users);
o Caching:
Example:
@Cacheable("users")
return userRepository.findById(id).orElse(null);
What to Highlight:
Spring Boot
Answer: Spring Boot simplifies Spring development with auto-configura on and embedded servers.
o Example:
@Service
@Autowired
this.repository = repository;
What to Highlight:
Answer: Stereotype annota ons mark classes for Spring’s component scanning.
Annota ons:
o @Repository: For data access classes; adds persistence excep on transla on.
Example:
@RestController
@Autowired
this.service = service;
@Service
@Autowired
this.repository = repository;
@Repository
Differences:
o Seman cs: @Service for logic, @Repository for data, @Controller for UI/API.
Interviewer Expecta on: The candidate should describe the Spring bean life cycle,
ini aliza on/destruc on methods, and bean scopes.
Answer:
5. Destruc on:
Bean Scopes:
o Example:
@Component
@Scope("prototype")
What to Highlight:
Interviewer Expecta on: The candidate should explain how to configure Spring Boot apps using
proper es/YAML and ini alize beans with @PostConstruct.
Answer:
Property Files:
proper es
spring.datasource.url=jdbc:mysql://localhost:3306/db
spring.datasource.username=user
spring.datasource.password=pass
myapp.feature.enabled=true
YAML:
yaml
spring:
datasource:
url: jdbc:mysql://localhost:3306/db
username: user
password: pass
myapp:
feature:
enabled: true
o Use @Value:
java
@Value("${myapp.feature.enabled}")
// Ge ers/Se ers
@PostConstruct:
o Example:
@Component
@PostConstruct
void init() {
What to Highlight:
Interviewer Expecta on: The candidate should explain REST principles, HTTP methods, mappings,
and advanced features like interceptors and naming conven ons.
Answer:
REST Principles:
Mappings:
XML/JSON:
Headers:
o Use @RequestHeader:
@GetMapping("/users")
Variables:
o Path: @PathVariable.
o Query: @RequestParam.
Interceptors:
o Example:
@Override
public boolean preHandle(H pServletRequest request, H pServletResponse response, Object
handler) {
return true;
@Configura on
@Override
registry.addInterceptor(new LoggingInterceptor());
What to Highlight:
Idempotency differences.
6. Excep on Handling
Interviewer Expecta on: The candidate should explain centralized excep on handling in Spring Boot
using @ControllerAdvice and custom excep ons.
Answer: Spring Boot provides robust excep on handling for REST APIs.
@ControllerAdvice:
o Example:
@ControllerAdvice
@ResponseStatus(H pStatus.NOT_FOUND)
public ErrorResponse handleUserNotFound(UserNotFoundExcep on ex) {
class ErrorResponse {
String error;
String message;
// Constructor, ge ers
o Example:
super(message);
@RestController
@GetMapping("/users/{id}")
Default Handling:
What to Highlight:
Interviewer Expecta on: The candidate should explain unit and integra on tes ng in Spring Boot,
using JUnit and Mockito, with examples.
Answer:
JUnit:
Mockito:
@SpringBootTest:
o Example:
@SpringBootTest
@Autowired
@Test
void testFindUser() {
assertNotNull(user);
assertEquals("Alice", user.getName());
o Example:
@ExtendWith(MockitoExtension.class)
@Mock
@Test
void testFindUser() {
when(repository.findById(1L)).thenReturn(Op onal.of(user));
assertEquals("Alice", result.getName());
verify(repository).findById(1L);
What to Highlight:
8. Spring Security (JWT, Access Tokens, TLS, SSL, Message Layer Security)
Interviewer Expecta on: The candidate should explain Spring Security basics, JWT implementa on,
and securing APIs with TLS/SSL.
Answer:
o Provides authen ca on (who you are) and authoriza on (what you can do).
o Example:
@Configura on
@EnableWebSecurity
@Bean
public SecurityFilterChain securityFilterChain(H pSecurity h p) throws Excep on {
h p
.requestMatchers("/public/**").permitAll()
.anyRequest().authen cated()
.h pBasic();
return h p.build();
o Steps:
o Example:
return Jwts.builder()
.setSubject(username)
.setIssuedAt(new Date())
.signWith(Keys.hmacShaKeyFor(secret.getBytes()))
.compact();
Configure filter:
// Validate token
chain.doFilter(request, response);
Access Tokens:
TLS/SSL:
yaml
server:
ssl:
key-store: classpath:keystore.p12
key-store-password: password
key-alias: alias
What to Highlight:
9. Repository
Interviewer Expecta on: The candidate should explain Spring Data JPA repositories, custom queries,
and best prac ces.
Basic Repository:
o Extend JpaRepository for CRUD opera ons.
o Example:
Custom Queries:
o Example:
java
@Query(value = "SELECT * FROM users WHERE age > ?1", na veQuery = true)
o Example:
java
List<User> findAll();
What to Highlight:
10. Maven/Gradle
Interviewer Expecta on: The candidate should compare Maven and Gradle, explain their
configura on, and discuss dependency management.
Answer:
Maven:
o XML-based (pom.xml).
o Example:
xml
<project>
<groupId>com.example</groupId>
<version>1.0</version>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<version>3.1.0</version>
</dependency>
</dependencies>
</project>
Gradle:
o Groovy/Kotlin-based (build.gradle).
o Example:
groovy
plugins {
dependencies {
implementa on 'org.springframework.boot:spring-boot-starter-web'
Comparison:
Dependency Management:
What to Highlight:
Interviewer Expecta on: The candidate should explain how Spring Boot connects to databases,
focusing on JPA and connec on pooling.
Answer: Spring Boot simplifies database connec ons with auto-configura on.
Configura on:
yaml
spring:
datasource:
url: jdbc:mysql://localhost:3306/db
username: user
password: pass
driver-class-name: com.mysql.cj.jdbc.Driver
jpa:
hibernate:
ddl-auto: update
show-sql: true
JPA Setup:
o Define en es:
java
@En ty
@Id
// Ge ers/Se ers
o Create repository:
java
Connec on Pool:
o HikariCP is default.
o Example:
java
@DataJpaTest
@Autowired
@Test
void testSave() {
user.setName("Alice");
repository.save(user);
assertEquals(1, repository.count());
}
What to Highlight:
Interviewer Expecta on: The candidate should explain Ka a’s basics, its use in Spring Boot, and a
simple producer/consumer example.
Answer:
Apache Ka a:
Spring Ka a:
o Dependency: spring-ka a.
Producer Example:
java
@Configura on
@Bean
config.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
config.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
config.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
@Bean
public Ka aTemplate<String, String> ka aTemplate() {
@Service
@Autowired
Consumer Example:
java
@Service
Configura on:
yaml
spring:
ka a:
bootstrap-servers: localhost:9092
consumer:
group-id: my-group
auto-offset-reset: earliest
What to Highlight:
Microservices
1. Design Pa erns
Interviewer Expecta on: The candidate should explain microservices-specific design pa erns like
Saga, CQRS, and Circuit Breaker, with examples.
Saga Pa ern:
o Manages distributed transac ons with local transac ons and compensa ng ac ons.
Example:
java
@Service
@Autowired
@Autowired
try {
orderService.createOrder(orderId);
paymentService.processPayment(orderId);
} catch (Excep on e) {
orderService.cancelOrder(orderId);
throw e;
}
Circuit Breaker:
o Example:
java
@CircuitBreaker(name = "paymentService")
Other Pa erns:
o API Gateway: Centralizes rou ng, auth (e.g., Spring Cloud Gateway).
What to Highlight:
2. Inter-Service Communica on
Interviewer Expecta on: The candidate should explain synchronous (REST) and asynchronous
(messaging) communica on, with examples.
Answer: Microservices communicate to collaborate on tasks.
Synchronous (REST/gRPC):
o Example (REST):
java
@RestController
@Autowired
@PostMapping("/orders")
Asynchronous (Messaging):
java
@Service
@Autowired
}
}
@Service
What to Highlight:
Interviewer Expecta on: The candidate should compare monolithic and microservices architectures,
discussing pros and cons with examples.
Answer:
Monolithic Architecture:
o Example: A Spring MVC app with all modules (user, order, payment) in one JAR.
o Advantages:
o Disadvantages:
Microservices Architecture:
o Advantages:
o Disadvantages:
Monitoring/debugging challenges.
When to Use:
What to Highlight:
Interviewer Expecta on: The candidate should explain techniques to make microservices resilient
and efficient, with prac cal examples.
Answer:
Resiliency:
Example:
java
@Retryable(maxA empts = 3, backoff = @Backoff(delay = 1000))
Example:
java
Efficiency:
Example: @Cacheable("users")
Example: repository.saveAll(users);
What to Highlight:
Interviewer Expecta on: The candidate should address hypothe cal scenarios, focusing on
availability and deployment solu ons.
Answer:
Service Availability:
o Solu on:
o Example:
java
@RestController
@GetMapping("/status")
Deployment Strategies:
o Solu on:
Blue-Green Deployment:
Canary Deployment:
Roll out to a small subset of users.
Rolling Updates:
Example:
yaml
apiVersion: apps/v1
kind: Deployment
spec:
strategy:
type: RollingUpdate
rollingUpdate:
maxSurge: 1
maxUnavailable: 0
What to Highlight:
Interviewer Expecta on: The candidate should elaborate on deployment strategies to minimize
down me and ensure smooth transi ons.
Answer:
Strategies:
o Blue-Green Deployment:
o Canary Deployment:
o Rolling Updates:
o Graceful Shutdown:
Spring Boot:
yaml
server:
shutdown: graceful
tomcat:
o Readiness Probes:
Example:
yaml
livenessProbe:
h pGet:
path: /actuator/health
port: 8080
readinessProbe:
h pGet:
path: /actuator/health
port: 8080
Tools:
What to Highlight:
Zero-down me goal.
Interviewer Expecta on: The candidate should describe how services interact in a microservices
architecture, from request to response.
Answer:
Process:
Example: h p://order-service/orders/123.
Example: DiscoveryClient.getInstances("payment-service").
Example:
java
Error Handling:
What to Highlight:
8. Service Discovery
Interviewer Expecta on: The candidate should explain service discovery, its importance, and tools
like Eureka or Consul.
Answer:
Service Discovery:
How It Works:
o Server Config:
yaml
spring:
applica on:
name: eureka-server
server:
port: 8761
eureka:
client:
register-with-eureka: false
fetch-registry: false
o Client Config:
yaml
spring:
applica on:
name: order-service
eureka:
client:
service-url:
defaultZone: h p://localhost:8761/eureka
o Code:
java
@RestController
@Autowired
@GetMapping("/call-payment")
Tools:
Benefits:
o Dynamic scaling.
What to Highlight:
9. Load Balancing
Interviewer Expecta on: The candidate should explain load balancing types (server-side and client-
side), algorithms, tools, and their role in microservices, with examples.
Answer:
Load Balancing:
o Distributes incoming traffic across mul ple service instances to ensure scalability,
reliability, and op mal resource use.
Types:
A dedicated load balancer (e.g., Nginx, AWS ELB, HAProxy) routes requests
to service instances.
nginx
upstream order_service {
server order-service1:8080;
server order-service2:8080;
server {
listen 80;
loca on /orders {
proxy_pass h p://order_service;
The client (or service) selects an instance using a library like Ne lix Ribbon
or Spring Cloud LoadBalancer.
java
@RestController
@Autowired
@Autowired
@GetMapping("/call-payment")
Algorithms:
o Least Connec ons: Routes to the instance with fewest ac ve connec ons.
Tools:
Role in Microservices:
What to Highlight:
Choosing algorithms based on workload (e.g., s cky sessions for stateful apps).
Interviewer Expecta on: The candidate should explain the role of an API Gateway, its features, and
how it’s implemented in microservices, with examples.
Answer:
API Gateway:
o A single entry point for client requests, rou ng them to appropriate microservices.
o Acts as a reverse proxy, handling cross-cu ng concerns like authen ca on, rate
limi ng, and logging.
Key Features:
o Rate Limi ng: Prevents abuse (e.g., max 100 requests/min per user).
o Dependency: spring-cloud-starter-gateway.
o Configura on:
yaml
spring:
cloud:
gateway:
routes:
- id: order_route
uri: lb://order-service
predicates:
- Path=/orders/**
- id: payment_route
uri: lb://payment-service
predicates:
- Path=/payments/**
java
@Component
@Override
exchange.getResponse().setStatusCode(H pStatus.UNAUTHORIZED);
return exchange.getResponse().setComplete();
return chain.filter(exchange);
Other Tools:
Benefits:
Challenges:
What to Highlight:
Interviewer Expecta on: The candidate should list common HTTP status codes, explain their
meanings, and describe their use in microservices APIs.
Answer: HTTP status codes indicate the result of a client request in a REST API.
Categories:
o 2xx (Success):
Use in Microservices:
o Example Controller:
java
@RestController
@RequestMapping("/users")
@GetMapping("/{id}")
if (id == 0) {
@PostMapping
// Save user
o Error Handling:
java
@ControllerAdvice
@ResponseStatus(H pStatus.BAD_REQUEST)
o Return precise codes (e.g., 404 over 400 for missing resources).
o Include error details in response body (e.g., { "error": "User not found", "details":
"ID 123" }).
What to Highlight:
Deployment CI/CD
Interviewer Expecta on: The candidate should explain Docker and Kubernetes, their components
(images, containers, pods), and communica on mechanisms, with examples.
Answer:
Docker:
o Docker Image: A read-only template with app code, dependencies, and run me.
dockerfile
FROM openjdk:17-jdk-slim
WORKDIR /app
COPY target/myapp.jar .
EXPOSE 8080
Build and run: docker build -t myapp . && docker run -p 8080:8080 myapp
Kubernetes:
o Orchestrates containers for scalability, availability, and management.
o Components:
o Example Deployment:
yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: order-service
spec:
replicas: 3
selector:
matchLabels:
app: order-service
template:
metadata:
labels:
app: order-service
spec:
containers:
- name: order-service
image: myapp:latest
ports:
- containerPort: 8080
---
apiVersion: v1
kind: Service
metadata:
name: order-service
spec:
selector:
app: order-service
ports:
- port: 80
targetPort: 8080
type: ClusterIP
o Between Pods:
Example Ingress:
yaml
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: app-ingress
spec:
rules:
- host: myapp.com
h p:
paths:
- path: /orders
pathType: Prefix
backend:
service:
name: order-service
port:
number: 80
What to Highlight:
2. Pipeline Stages
Interviewer Expecta on: The candidate should describe the stages of a CI/CD pipeline, their
purpose, and tools used.
Answer: A CI/CD pipeline automates building, tes ng, and deploying code.
Stages:
o 1. Code Commit:
o 2. Build:
Compile code, resolve dependencies, and create ar facts (e.g., JAR, Docker
image).
o 3. Test:
yaml
- name: Run Tests
o 4. Code Analysis:
o 6. Push to Registry:
o 7. Deploy to Staging:
o 8. Acceptance Tests:
o 10. Monitor:
Tools:
yaml
on:
push:
branches: [ main ]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: ac ons/checkout@v3
uses: ac ons/setup-java@v3
with:
java-version: '17'
run: |
What to Highlight:
Interviewer Expecta on: The candidate should explain tools like Prisma Scan and Checkmarx, their
role in CI/CD, and how they ensure secure code.
Answer:
Code Quality:
o Tools:
SonarQube: Analyzes code for bugs, code smells, and test coverage.
yaml
Vulnerability Checks:
o Prisma Scan:
Part of Palo Alto’s Prisma Cloud; scans IaC, containers, and code.
o Checkmarx:
Example: Finds SQL injec on risks in String query = "SELECT * FROM users
WHERE id = " + userId;.
Integra on: Run cx scan in Jenkins; block PRs with cri cal vulnerabili es.
o Dependency Scanning:
o Fail builds for cri cal issues only to avoid blocking progress.
What to Highlight:
Interviewer Expecta on: The candidate should describe a complete deployment process, from
code to produc on, emphasizing automa on and reliability.
Answer:
End-to-End Deployment Strategy:
1. Code Commit:
3. Security Scans:
4. Docker Build:
5. Deploy to Staging:
yaml
apiVersion: apps/v1
kind: Deployment
spec:
strategy:
type: RollingUpdate
rollingUpdate:
maxSurge: 1
maxUnavailable: 0
8. Post-Deployment:
Example Workflow:
yaml
name: Deploy
on:
push:
branches: [ main ]
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: ac ons/checkout@v3
run: |
run: |
What to Highlight:
Zero-down me deployments.
Interviewer Expecta on: The candidate should explain how servers and instances are managed,
traffic handling, and update strategies in a cloud environment.
Answer:
Servers and Instances:
Handling Traffic:
o Auto-Scaling:
Example:
yaml
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: order-service
spec:
scaleTargetRef:
kind: Deployment
name: order-service
minReplicas: 2
maxReplicas: 10
metrics:
- type: Resource
resource:
name: cpu
target:
type: U liza on
o Strategies:
o Graceful Shutdown:
yaml
spec:
template:
spec:
termina onGracePeriodSeconds: 30
o Zero-Down me Example:
Deploy new pods, wait for readiness, then drain old pods.
What to Highlight:
Interviewer Expecta on: The candidate should explain OpenShi basics, focusing on secret maps,
config maps, and differences from Kubernetes.
Answer:
OpenShi :
o Red Hat’s Kubernetes-based pla orm with added developer and opera onal tools.
o Extends Kubernetes with features like built-in CI/CD (Tekton), image registry, and
stricter security.
Secret Map:
o Example:
yaml
apiVersion: v1
kind: Secret
metadata:
type: Opaque
data:
o Usage in Pod:
yaml
spec:
containers:
- name: app
env:
- name: DB_USER
valueFrom:
secretKeyRef:
key: username
Config Map:
yaml
apiVersion: v1
kind: ConfigMap
metadata:
name: app-config
data:
db.url: jdbc:mysql://db:3306/myapp
log.level: DEBUG
o Usage:
yaml
spec:
containers:
- name: app
env:
- name: DB_URL
valueFrom:
configMapKeyRef:
name: app-config
key: db.url
Example:
yaml
kind: Route
metadata:
name: order-service
spec:
to:
kind: Service
name: order-service
port:
targetPort: 8080
Use Case:
What to Highlight:
Since the document lists Design Pa erns under Microservices, and we’ve already covered the Saga
pa ern extensively (orchestra on and choreography examples in Java microservices), I’ll briefly
summarize it here to ensure completeness and cover other relevant pa erns not yet discussed.
Interviewer Expecta on: The candidate should explain microservices-specific design pa erns,
focusing on their purpose, implementa on, and trade-offs, with emphasis on Saga and others like
CQRS, Event Sourcing, and Circuit Breaker.
Answer:
o Manages distributed transac ons across microservices with local transac ons and
compensa ng ac ons.
o Choreography:
@Service
@Autowired
@Service
if ("FAIL".equals(orderId)) {
return;
o Orchestra on:
o Example:
Implementa on:
@Service
@Autowired
repository.save(order);
@Service
@Autowired
Event Sourcing:
o Example:
Implementa on:
events.add(event);
if (event.getOrderId().equals(orderId)) {
order.apply(event);
return order;
Circuit Breaker:
@RestController
@Autowired
@GetMapping("/call-payment")
Other Pa erns:
o Database per Service: Each service has its own database for decoupling.
What to Highlight: