Nik Java Interview Notes 2
Nik Java Interview Notes 2
🔹 2. Collections Framework
🔹 4. Exception Handling
🔹 5. Java 8 Features
🔹 6. Java 17 Features
🔹 7. Java 21 Features
🔵 Q1: What are the key differences between Java 8 and Java 17?
Answer:
Answer:
Answer:
Answer:
Answer:
• == checks reference equality (whether two references point to the same object).
• .equals() checks value equality (whether two objects contain the same data).
Answer:
Answer:
Answer:
Answer:
Answer:
Answer:
Answer:
🔹 3. Spring MVC
🔹 4. Spring Security
🔹 2. Caching Strategies
🔹 3. Transaction Management
Answer:
Annotation Purpose
Answer:
Answer:
Answer:
Answer:
Annotation Purpose
Returns response as JSON/XML (combines @Controller +
@RestController
@ResponseBody).
Used for MVC applications that return views (e.g., JSP,
@Controller
Thymeleaf).
Answer:
Method Description
Creates a new record, returns the generated
save()
ID.
persist() Similar to save(), but does not return the ID.
Merges detached entities into the persistence
merge()
context.
Answer:
Nikhlesh Patle -@iamnikspatle
Java Interview Mastery Guide
Answer:
Answer:
Annotation Usage
Extracts query parameters from URL (e.g.,
@RequestParam
/users?name=John).
Extracts path parameters from URL (e.g.,
@PathVariable
/users/{id}).
Answer:
Answer:
Answer:
• Use PagingAndSortingRepository.
• Implement Pageable and Page interfaces.
• Example: Page<User> findByName(String name, Pageable pageable);
Important Problems:
Reverse an Array
Two Sum (Using HashMap)
Longest Substring Without Repeating Characters
Kadane’s Algorithm (Max Subarray Sum)
🔹 2. Linked Lists
Important Problems:
Reverse a Linked List (Iterative & Recursive)
Merge Two Sorted Linked Lists
Detect & Remove Cycle in a Linked List
Important Problems:
Implement Stack using Queue
Next Greater Element
LRU Cache Implementation
Important Problems:
First Non-Repeating Character in a String
Count Distinct Elements in an Array
Find Pair with Given Sum
Important Problems:
Lowest Common Ancestor (LCA) in BST
Validate Binary Search Tree
Level Order Traversal
Important Problems:
Detect Cycle in a Graph
Topological Sorting
Word Ladder Problem
Important Problems:
Find Kth Smallest Element
Search in Rotated Sorted Array
Count Inversions in an Array
Important Problems:
0/1 Knapsack Problem
Longest Increasing Subsequence
Edit Distance (String Transformation)
Approach: Use Floyd’s Cycle Detection Algorithm (Tortoise & Hare Method).
Steps:
Java Code:
class ListNode {
int val;
ListNode next;
ListNode(int val) { this.val = val; this.next = null; }
}
class ListNode {
int val;
ListNode next;
ListNode(int val) { this.val = val; this.next = null; }
}
Java HashMap uses chaining with linked lists for handling collisions. From Java 8
onwards, it uses balanced trees (red-black trees) when the number of collisions
increases, improving lookup performance from O(N) to O(log N).
BFS (Breadth-First Search): Uses a queue (FIFO), explores neighbors first, and is ideal
for finding shortest paths in unweighted graphs.
DFS (Depth-First Search): Uses a stack (or recursion), explores deeper paths first, and
is useful for detecting cycles and solving connectivity problems.
import java.util.*;
queue.add(start);
visited.add(start);
while (!queue.isEmpty()) {
int node = queue.poll();
System.out.print(node + " ");
if (!visited.contains(neighbor)) {
queue.add(neighbor);
visited.add(neighbor);
}
}
}
}
}
🔵 Q5: What is the difference between Merge Sort and Quick Sort?
Merge Sort:
• Uses Divide & Conquer, splits array into halves, sorts, and merges them.
• Time Complexity: O(N log N) (Always)
• Space Complexity: O(N) (Uses extra space for merging)
• Stable Sort: Yes
Quick Sort:
Monolithic: Single codebase, tightly coupled, easy deployment but difficult to scale.
Microservices: Independent services, loosely coupled, scalable but requires API
Gateway, Service Discovery, and Inter-Service Communication.
Singleton: Ensures only one instance of a class exists (used in logging, caching).
Factory Pattern: Creates objects without specifying the exact class (used in Database
Connections).
Observer Pattern: Implements event-driven behavior (used in Notification Systems).
Strategy Pattern: Defines a family of algorithms and selects one at runtime (used in
Payment Processing).
Proxy Pattern: Acts as an intermediary to control access (used in API Rate Limiting).
🔹 3. Caching Strategies
Load Balancers: Distribute traffic across multiple servers (Round Robin, Least
Connections).
API Gateways: Manage traffic, security, and authentication (Kong, Nginx, AWS API
Gateway).
Rate Limiting: Prevent excessive API calls (Token Bucket, Leaky Bucket).
java
CircuitBreaker circuitBreaker =
CircuitBreaker.ofDefaults("backendService");
Supplier<String> supplier =
CircuitBreaker.decorateSupplier(circuitBreaker,
() -> backendService.getData());
Use Cases: Protects microservices from overloading, API failures, and dependency
crashes.
🔵 Q2: What are the key differences between Load Balancers & API
Gateways?
Load Balancer:
API Gateway:
Range-Based Sharding: Divide data based on a range (e.g., ID 1-1000 → Shard 1).
Hash-Based Sharding: Use a hash function to distribute data evenly.
Geolocation-Based Sharding: Store region-specific data in nearby servers.
Dynamic Sharding: Add more shards dynamically (used in NoSQL databases like
MongoDB, Cassandra).
Kafka Architecture:
CAP Theorem States: A distributed system cannot achieve all three simultaneously:
Examples:
🔵 Q7: What are the differences between SQL and NoSQL databases?
Token Bucket Algorithm: Assigns tokens to requests and refills over time.
Leaky Bucket Algorithm: Controls request flow at a fixed rate.
Implementation:
Answer:
BEGIN;
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
COMMIT;
🔹 1. CI/CD Pipelines
Yaml:
stages:
- build
- test
- deploy
build-job:
stage: build
script:
- echo "Building application..."
- mvn clean package
test-job:
stage: test
script:
- echo "Running tests..."
- mvn test
deploy-job:
stage: deploy
script:
- echo "Deploying to server..."
- scp target/app.jar user@server:/opt/app
Yaml:
apiVersion: apps/v1
kind: Deployment
metadata:
name: my-app
spec:
replicas: 3
selector:
matchLabels:
app: my-app
template:
metadata:
labels:
app: my-app
spec:
containers:
- name: my-app-container
image: my-app:latest
ports:
- containerPort: 8080
Hcl:
provider "aws" {
region = "us-east-1"
}
Docker:
Kubernetes:
Example:
A Pod is the smallest deployable unit in Kubernetes that can contain one or more
containers.
Key Features:
Yaml:
apiVersion: v1
kind: Pod
metadata:
name: multi-container-pod
spec:
containers:
- name: app-container
image: my-app
- name: logging-container
image: log-collector
Yaml:
apiVersion: v1
kind: Service
metadata:
name: my-service
spec:
type: NodePort
selector:
app: my-app
ports:
- protocol: TCP
port: 80
targetPort: 8080
nodePort: 30007
Steps:
Groovy:
pipeline {
agent any
stages {
stage('Build') {
steps {
sh 'docker build -t my-app:latest .'
}
}
stage('Push') {
steps {
sh 'docker push my-app:latest'
}
}
stage('Deploy') {
steps {
sh 'kubectl apply -f deployment.yaml'
}
}
}
}
Yaml:
apiVersion: v2
name: nginx-chart
description: A Helm chart for Nginx
version: 1.0.0
Bash:
Yaml:
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: mysql
spec:
serviceName: "mysql"
replicas: 3
selector:
matchLabels:
app: mysql
template:
Nikhlesh Patle -@iamnikspatle
Java Interview Mastery Guide
metadata:
labels:
app: mysql
spec:
containers:
- name: mysql
image: mysql:latest
Key Strategies:
Yaml:
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: my-app-hpa
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: my-app
minReplicas: 2
maxReplicas: 10
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 50