0% found this document useful (0 votes)
51 views60 pages

1770978921182

The document outlines fundamental Java concepts including the differences between JDK, JRE, and JVM, features of Java, primitive data types, and access modifiers. It also covers object-oriented programming principles such as inheritance, polymorphism, encapsulation, and abstraction, along with exception handling and collection frameworks. Additionally, it introduces Spring Boot, its advantages, and key annotations like @SpringBootApplication and @Autowired.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
51 views60 pages

1770978921182

The document outlines fundamental Java concepts including the differences between JDK, JRE, and JVM, features of Java, primitive data types, and access modifiers. It also covers object-oriented programming principles such as inheritance, polymorphism, encapsulation, and abstraction, along with exception handling and collection frameworks. Additionally, it introduces Spring Boot, its advantages, and key annotations like @SpringBootApplication and @Autowired.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Basic Concepts

1. What is the difference between JDK, JRE, and JVM?

 JVM (Java Virtual Machine):

o It is the runtime environment that executes Java bytecode.

o It is platform-dependent (Windows JVM, Linux JVM, etc.).

o Responsibilities: loads, verifies, and executes bytecode.

 JRE (Java Runtime Environment):

o Provides the libraries, JVM, and other files necessary to run Java applications.

o Does not include development tools (compiler, debugger).

o Used to run programs only.

 JDK (Java Development Kit):

o A superset of JRE + development tools (javac, javadoc, debugger).

o Required for developing and running Java applications.

o Contains JRE + compiler + tools.

👉 Summary: JDK = JRE + development tools; JRE = JVM + libraries; JVM = runs bytecode.

2. What are the main features of Java (OOP principles)?

1. Object-Oriented: Everything in Java is treated as an object (except primitives).

2. Platform Independent: Java programs compile into bytecode, which can run on any JVM.

3. Simple: Syntax is easy, similar to C++.

4. Secure: Java has no explicit pointers, has security managers, and supports bytecode
verification.

5. Robust: Strong memory management and exception handling.

6. Portable: Bytecode can run on any platform.

7. Multithreaded: Java supports concurrent execution using threads.

8. High Performance: JIT (Just-In-Time) compiler increases speed.

9. Distributed: Supports RMI (Remote Method Invocation), web-based apps.

3. What are primitive data types in Java?

Java has 8 primitive data types:

 byte (8-bit)
 short (16-bit)

 int (32-bit)

 long (64-bit)

 float (32-bit decimal)

 double (64-bit decimal)

 char (16-bit Unicode character)

 boolean (true/false)

4. What is autoboxing and unboxing?

 Autoboxing: Automatic conversion of primitive types → wrapper objects.

 int num = 10;

 Integer obj = num; // autoboxing

 Unboxing: Automatic conversion of wrapper objects → primitive types.

 Integer obj = 20;

 int num = obj; // unboxing

5. What are access modifiers in Java (private, protected, public, default)?

 private: Accessible only within the same class.

 default (no modifier): Accessible within the same package.

 protected: Accessible within the same package + subclasses (even in other packages).

 public: Accessible everywhere.

6. What is a package in Java?

 A package is a collection of classes, interfaces, and sub-packages.

 Used for code reusability, modularity, and avoiding name conflicts.

 Example:

 package mypackage;

 public class MyClass {}

7. What is a static keyword? Static variables and methods?

 static keyword: Belongs to the class, not objects.


 Static Variable: One copy per class, shared among objects.

 static int count;

 Static Method: Can be called without creating an object. Cannot access non-static variables
directly.

 static void display() {}

 Static Block: Executes once when the class is loaded.

8. What is a Constructor in Java? Types of constructors?

 A constructor is a special method used to initialize objects.

 Same name as class, no return type.

 Types:

1. Default Constructor: No arguments.

2. Parameterized Constructor: Takes parameters.

3. Copy Constructor (not built-in but can be defined): Copies values from another
object.

9. Can we use static methods in a Constructor?


 Yes, static methods can be called inside a constructor, but constructors themselves cannot
be static.

 Example:

 class Test {

 static void greet() { [Link]("Hello"); }

 Test() { greet(); } // calling static method inside constructor

 }

OOP Concepts

10. What is inheritance? Types of inheritance in Java?

 Inheritance: Mechanism where one class (child/subclass) acquires properties & methods of
another class (parent/superclass).

 Promotes code reusability.

 Types in Java:

1. Single Inheritance: One class extends another.


2. Multilevel Inheritance: A class inherits from a child class.

3. Hierarchical Inheritance: Multiple classes inherit from one superclass.

4. Hybrid (through interfaces): Combination using interfaces.

👉 Note: Java does not support multiple inheritance with classes (to avoid ambiguity), but supports
it with interfaces.

11. What is polymorphism? Give examples

 Polymorphism: Ability of an object to take many forms.

 Types:

1. Compile-time (Overloading):

2. class Math {

3. int add(int a, int b) { return a+b; }

4. double add(double a, double b) { return a+b; }

5. }

6. Runtime (Overriding):

7. class Animal { void sound(){ [Link]("Animal sound"); } }

8. class Dog extends Animal { void sound(){ [Link]("Bark"); } }

12. What is encapsulation and abstraction?


 Encapsulation: Wrapping data (variables) and methods together in a class. Achieved by
private variables + public getters/setters.
 Abstraction: Hiding implementation details and showing only essential features. Achieved by
abstract classes & interfaces.

13. What is method overloading vs method overriding?

 Overloading: Same method name, different parameter list (compile-time polymorphism).

 Overriding: Subclass provides a new implementation of a parent class method (runtime


polymorphism).

 Example:

 class Parent { void show(){} }

 class Child extends Parent { @Override void show(){} }


14. When to use Interface vs Abstract Class?

 Use Interface when:

o You need multiple inheritance.

o You want to define only method signatures.

 Use Abstract Class when:

o You want to share code among related classes.

o You need both abstract & concrete methods.

 Rule: If behavior is common → abstract class; if behavior is contract-based → interface.

15. What is a Marker Interface? Why use it?

 Marker Interface: An interface with no methods/fields (empty).

 Used to signal to JVM/Compiler about a special behavior.

 Example: Serializable, Cloneable.

 JVM checks if a class implements them and applies special processing.

String Handling

16. What is the difference between String, StringBuilder, and StringBuffer?

 String: Immutable (cannot be changed once created). Stored in String pool.

 StringBuilder: Mutable, faster, not thread-safe.

 StringBuffer: Mutable, thread-safe (synchronized) but slower.

17. Difference between creating String with literal and new operator

 Using Literal:

 String s1 = "Hello";

 String s2 = "Hello"; // refers to same object in String Pool

 Using new Operator:

 String s3 = new String("Hello"); // creates a new object in heap

 Difference: Literal reuses memory in the String pool, while new always creates a new object.

String Handling

18. What is String pool and how does it work?


 String pool (String Intern Pool):

o A special memory region inside the heap where Java stores string literals.

o When a string is created with a literal, JVM first checks the pool.

o If the string exists, it returns the reference; if not, it creates a new one.

 Example:

 String s1 = "Hello";

 String s2 = "Hello"; // s2 will point to same object as s1

 This saves memory and improves performance.

19. What are the advantages of String pool?

1. Memory efficiency (reuses existing strings).

2. Performance optimization (avoids creating duplicate objects).

3. Immutability support (safe to share strings).

20. Why String is immutable?

 Security: Strings are used in class loading, DB URLs, networking.

 Hashing: Since hashcode is cached, immutable strings ensure consistency when used as keys
in HashMap.

 Thread safety: Multiple threads can safely share strings.

 Performance: String pool relies on immutability.

Basic Collections

21. What is a Collection in Java?

 Collection Framework: A set of interfaces and classes to store/manipulate groups of objects.

 Provides ready-made data structures (List, Set, Map).

 Located in [Link] package.

22. Difference between Array and ArrayList?

 Array:

o Fixed size.

o Can store primitives & objects.


o Faster access.

 ArrayList:

o Dynamic size.

o Stores only objects.

o Slower than array (resizing overhead).

23. What is the difference between ArrayList and LinkedList?

 ArrayList:

o Uses dynamic array.

o Fast random access (O(1)).

o Slow insertion/deletion (O(n)).

 LinkedList:

o Uses doubly linked list.

o Slow access (O(n)).

o Fast insertion/deletion (O(1) if pointer known).

24. What is a HashMap? Basic operations?

 HashMap: Stores data in key-value pairs using hash table.

 Keys must be unique, values can duplicate.

 Allows one null key, multiple null values.

 Operations:

o put(key, value)

o get(key)

o remove(key)

o containsKey(key)

25. What is the difference between HashSet and TreeSet?

 HashSet:

o Stores unique elements.

o No ordering.

o Allows one null.


o Backed by HashMap.

 TreeSet:

o Stores unique elements in sorted order.

o No nulls allowed.

o Backed by TreeMap (Red-Black tree).

26. What is an Iterator?

 Iterator: Used to traverse collections.

 Methods:

o hasNext() → checks if next element exists.

o next() → returns next element.

o remove() → removes element safely during iteration.

27. What is the difference between List and Set?

 List:

o Allows duplicates.

o Maintains insertion order.

 Set:

o No duplicates.

o Order not guaranteed (except LinkedHashSet/TreeSet).

28. Array vs List?

 Array:

o Fixed size.

o Stores primitives & objects.

 List (ArrayList, LinkedList):

o Dynamic size.

o Only objects.

29. Set vs List?

 Set:
o Unique elements only.

o Order not guaranteed.

 List:

o Allows duplicates.

o Ordered.

Exception Handling

30. What is an Exception? Types of exceptions?

 Exception: An unwanted event disrupting normal program flow.

 Types:

1. Checked (compile-time): e.g., IOException, SQLException.

2. Unchecked (runtime): e.g., NullPointerException, ArithmeticException.

3. Errors: Serious issues (OutOfMemoryError, StackOverflowError).

31. What is the difference between checked and unchecked exceptions?

 Checked: Must be handled at compile-time (try-catch or throws).

 Unchecked: Occurs at runtime, not checked by compiler.

32. What is try-catch-finally block?

 try: Code that may throw exception.

 catch: Handles the exception.

 finally: Always executes (used for cleanup, closing connections).

33. Can we use try without catch?

 Yes, but must have finally.

 try {

 // code

 } finally {

 // cleanup

 }
34. What is throw vs throws?

 throw: used inside method to throw an exception.

 throws: used in method signature to declare possible exceptions.

35. What are the use cases of creating user-defined exceptions?

 For application-specific errors.

 Example: Banking application → InsufficientFundsException.

 Helps improve readability & control.

36. How to handle user-defined exception?

 Extend Exception class.

 Example:

 class MyException extends Exception {

 MyException(String msg) { super(msg); }

 }

37. What is a NullPointerException & how to prevent it?

 NPE: Occurs when calling methods/variables on null object.

 Prevention:

o Null checks (if(obj != null)).

o Use [Link]().

o Use Optional class.

38. What is a ClassCastException?

 Occurs when casting object to an incompatible type.

 Object obj = new String("Hello");

 Integer i = (Integer) obj; // ClassCastException

39. What is Error vs Exception?

 Exception: recoverable (e.g., FileNotFoundException).

 Error: serious issue, not recoverable (e.g., OutOfMemoryError).


Q40. Explain the difference between break and continue statements.

 break: Exits the loop completely, regardless of the condition. Used when you want to stop
iteration early.

 continue: Skips the current iteration and moves to the next one. Loop execution continues.

Example:

for (int i = 1; i <= 5; i++) {

if (i == 3) continue; // skip 3

if (i == 5) break; // stop when 5

[Link](i);

// Output: 1 2 4

Q41. What is the difference between == and .equals()?

 ==: Compares references (memory addresses). Used for primitives and checking if two
objects point to the same location.

 .equals(): Compares object content (overridden in classes like String).

String a = new String("Hello");

String b = new String("Hello");

[Link](a == b); // false (different objects)

[Link]([Link](b)); // true (same content)

🌱 Spring Boot Basics

Q42. What is Spring Boot?


Spring Boot is a framework built on top of Spring that simplifies Java application
development by:

 Providing defaults and auto-configuration.

 Reducing boilerplate setup.

 Allowing quick creation of production-ready applications.

Q43. What are the advantages of Spring Boot?

 Auto-configuration (minimal XML/config).

 Embedded servers (Tomcat/Jetty).


 Easy integration with Spring ecosystem.

 Production-ready features (actuator, monitoring).

 Microservices-friendly.

Q44. What is @SpringBootApplication annotation?


It’s a convenience annotation that combines:

 @Configuration → Marks class as configuration source.

 @EnableAutoConfiguration → Enables Spring Boot auto-config.

 @ComponentScan → Scans packages for components.

Q45. What is the difference between @Component, @Service, and @Repository?

 @Component: Generic Spring-managed bean.

 @Service: Specialization of @Component, used for business logic.

 @Repository: Specialization of @Component, used for data access (DAO). Adds exception
translation.

Q46. What is Dependency Injection (DI)?


DI is a design pattern where the framework provides dependencies (objects) instead of the
class creating them.

 Promotes loose coupling.

 Implemented via constructors, setters, or field injection.

Q47. What is @Autowired?

 Used to inject dependencies automatically.

 Can be applied on fields, constructors, or setters.

@Service

class OrderService {

@Autowired

private PaymentService paymentService; // injected automatically

}
Q48. What are Spring Boot starters?
Pre-configured Maven/Gradle dependencies that bundle common libraries.
Examples:

 spring-boot-starter-web → for web apps (Tomcat, Spring MVC).

 spring-boot-starter-data-jpa → for JPA and Hibernate.

 spring-boot-starter-security → for authentication/authorization.

Q49. What is [Link] file?


A configuration file used to define application-specific properties (port, DB connection,
logging).
Example:

[Link]=8081

[Link]=jdbc:mysql://localhost:3306/test

Q50. Difference between Spring and Spring Boot?

 Spring: Core framework, needs manual setup, XML/Java config.

 Spring Boot: Built on Spring, provides auto-config, embedded server, faster setup.

Q51. What is IOC container in Spring?


IOC (Inversion of Control) container manages object creation, wiring, and lifecycle.

 Implemented using ApplicationContext.

 Provides DI (Dependency Injection).

🌍 REST API Basics

Q52. What is HTTP? Common HTTP methods?


HTTP (HyperText Transfer Protocol) is the foundation of web communication.
Common methods:

 GET → Retrieve data.

 POST → Create data.

 PUT → Update data.

 DELETE → Delete data.

 PATCH → Partial update.


Q53. What are HTTP status codes (200, 404, 500)?

 200 OK: Successful request.

 404 Not Found: Resource not available.

 500 Internal Server Error: Server-side issue.

Q54. What is REST API?


REST (Representational State Transfer) is an architectural style for APIs.

 Uses HTTP methods for CRUD operations.

 Stateless communication.

 Resource-based (identified via URLs).

Q55. What is JSON?


JSON (JavaScript Object Notation): Lightweight data format for exchanging data.
Example:

"id": 1,

"name": "John",

"role": "Developer"

Q56. What is @RestController vs @Controller?

 @Controller: Returns views (like JSP/Thymeleaf).

 @RestController: Combines @Controller + @ResponseBody, returns JSON/XML directly.

Q57. What is the process of creating a REST API (with example)?

Steps:

1. Create Spring Boot project (spring-boot-starter-web).

2. Define a model class.

3. Create a controller with endpoints.

Example:

@RestController

@RequestMapping("/api/users")
public class UserController {

@GetMapping("/{id}")

public User getUser(@PathVariable int id) {

return new User(id, "John", "Developer");

➡ GET /api/users/1 returns JSON:

"id": 1,

"name": "John",

"role": "Developer"

58. Contract between hashCode() and equals() methods?

 Contract Rules:

1. If two objects are equal (equals() returns true), then their hashCode() must be the
same.

2. If two objects are not equal, their hashCode() may be same (collision possible), but
ideally should be different for efficiency.

 Reason: Collections like HashMap, HashSet rely on hashCode() to group objects into buckets
and equals() to resolve collisions.

 Example:

 class Employee {

 int id;

 String name;

 public int hashCode() { return id; }

 public boolean equals(Object o) {

 if (this == o) return true;

 if (!(o instanceof Employee)) return false;

 return [Link] == ((Employee)o).id;

 }
 }

59. Explain the internal working of HashMap in Java

1. Hashing: Key’s hashCode() determines bucket index via (hash & (n-1)).

2. Storage: Each bucket contains a linked list or red-black tree (Java 8+) of entries.

3. Collision Handling: If multiple keys map to the same bucket:

o Before Java 8: stored in linked list

o Java 8+: converted to tree if >8 entries (to improve performance from O(n) → O(log
n)).

4. Resize: When load factor (size/capacity) exceeds threshold (default 0.75), capacity doubles,
and entries are rehashed.

60. What happens on a HashMap collision?

 If two keys have same bucket index:

o equals() is used to check if keys are the same.

o If same → value is updated.

o If different → new entry added to bucket’s chain/tree.

61. What is the load factor in HashMap?

 Definition: Load factor = size / capacity.

 Default: 0.75 → HashMap resizes when 75% full.

 Tradeoff: Higher load factor → less space wasted, more collisions. Lower → more space,
fewer collisions.

62. Difference between HashMap, LinkedHashMap, and TreeMap

Feature HashMap LinkedHashMap TreeMap

Sorted by key
Order Unordered Insertion order
(natural/comparator)

Performance O(1) O(1) O(log n)

1 null key,
Nulls Same as
many null No null key
Allowed? HashMap
values
63. Difference between HashMap, LinkedHashMap, and ConcurrentHashMap

 HashMap → Not thread-safe, null allowed.

 LinkedHashMap → Same but preserves insertion order.

 ConcurrentHashMap → Thread-safe, uses segment locking (not whole map), nulls not
allowed.

64. How can you convert a HashMap into an ArrayList?

HashMap<Integer, String> map = new HashMap<>();

[Link](1, "A"); [Link](2, "B");

// Convert to list of keys

List<Integer> keys = new ArrayList<>([Link]());

// Convert to list of values

List<String> values = new ArrayList<>([Link]());

// Convert to list of entries

List<[Link]<Integer,String>> entries = new ArrayList<>([Link]());

65. Differences between Comparable and Comparator

 Comparable: Natural ordering, defined in the class using compareTo().

 Comparator: Custom ordering, defined externally with compare().

 Example:

 class Student implements Comparable<Student> {

 int marks;

 public int compareTo(Student s) { return [Link] - [Link]; }

 }

 Comparator<Student> byName = (a,b) -> [Link]([Link]);


66. What is a ConcurrentHashMap? How does it work?

 Thread-safe HashMap.

 Uses bucket-level locking (segment-based in Java 7) and CAS + synchronized blocks (Java 8).

 Multiple threads can read/write without blocking entire map.

 Null keys/values not allowed.

67. Difference between Hashtable and ConcurrentHashMap

Feature Hashtable ConcurrentHashMap

Synchronization Entire map locked Bucket-level or CAS

Performance Slower Faster in concurrent env

Nulls Allowed No No

Introduced Legacy (JDK 1.0) Modern (JDK 1.5)

68. Difference between Vector and ArrayList

Feature Vector ArrayList

Sync Thread-safe (synchronized) Not synchronized

Performance Slower Faster

Legacy? Yes (JDK 1.0) Modern replacement

Growth Doubles size 50% growth

69. HashMap vs HashTable

 HashMap: Non-synchronized, allows one null key & multiple null values.

 Hashtable: Synchronized, no nulls, legacy.

70. ArrayList vs LinkedList

Feature ArrayList LinkedList

Storage Dynamic array Doubly linked nodes

Access O(1) random access O(n) traversal


Feature ArrayList LinkedList

Insert/Delete O(n) O(1) at head/tail

Memory Less overhead More (pointers overhead)

📘 Java 8 Features (Q71 – Q77)

71. What is a Functional Interface?

 An interface with exactly one abstract method.

 Can have default & static methods.

 Used in Lambda expressions.

 Example:

 @FunctionalInterface

 interface MyFunc {

 void greet();

 }

72. Explain Java 8 features (Lambdas, Streams, Optional)

 Lambda Expressions → Concise way to represent anonymous methods.

 Stream API → Functional-style operations on collections (filter, map, reduce).

 Optional → Container to handle null safely, avoiding NullPointerException.

73. Difference between map() vs flatMap() in Java 8?

 map() → Transforms elements, returns Stream<T>.

 flatMap() → Flattens nested structures, returns Stream<T> directly.

 Example:

 List<List<Integer>> list = [Link]([Link](1,2), [Link](3,4));

 [Link]().map(l -> [Link]()).forEach([Link]::println); // Stream<Stream<Integer>>

 [Link]().flatMap(l -> [Link]()).forEach([Link]::println); // Stream<Integer>

74. What is Stream API and its advantages?

 Declarative processing of collections.


 Advantages:

o Reduces boilerplate.

o Parallel processing support.

o Cleaner, functional code.

75. What is Stream pipeline?

 A sequence of operations on a Stream.

 Consists of:

1. Source (collection, array, file, etc.)

2. Intermediate operations (filter, map, sorted)

3. Terminal operation (collect, forEach, reduce)

76. Difference between intermediate and terminal operators in Stream API

 Intermediate: Return Stream, lazy (filter, map, flatMap, sorted).

 Terminal: Produce result/non-stream (collect, reduce, forEach).

77. Using Stream API, find the 2nd highest salary from employee objects list

List<Employee> employees = [Link](

new Employee("A", 5000),

new Employee("B", 7000),

new Employee("C", 6000),

new Employee("D", 8000)

);

Optional<Integer> secondHighest = [Link]()

.map(Employee::getSalary)

.distinct()

.sorted([Link]())

.skip(1)

.findFirst();
[Link]([Link]::println);

Java 8 & Functional Programming

78. Use of Stream API in projects

 Simplifies bulk data processing.

 Enables functional-style operations (map, filter, reduce).

 Eliminates boilerplate loops.

 Improves readability & maintainability.


 Example use cases: filtering employees, grouping transactions, calculating averages,
processing logs.

79. Lambda Expressions vs Anonymous Classes

 Lambda Expressions

o Introduced in Java 8.

o Provide a concise syntax for functional interfaces.

o Example:

o Runnable r = () -> [Link]("Running");

 Anonymous Classes

o Older way (before Java 8).

o More verbose.

o Example:

o Runnable r = new Runnable() {

o public void run() {

o [Link]("Running");

o }

o };

✅ Difference: Lambdas are shorter, clearer, and allow functional programming, while
anonymous classes are more flexible (can define multiple methods).

Advanced OOP
80. What is a Functional Interface?

 An interface with exactly one abstract method.

 Can have multiple default or static methods.

 Used with Lambda expressions.

 Examples: Runnable, Callable, Comparator, Consumer.

81. Sealed Classes (Java 17)

 Restrict which classes can extend/implement them.

 Declared using sealed, permits, and non-sealed.

 Example:

 public sealed class Shape permits Circle, Square {}

 public final class Circle extends Shape {}

 public non-sealed class Square extends Shape {}

✅ Helps in controlled inheritance and better modeling.

82. Fail-Fast Iteration & Handling

 Fail-Fast iterators throw ConcurrentModificationException if collection is modified


structurally during iteration.

 Example: ArrayList, HashMap.


 Handling: Use [Link]() instead of modifying directly OR use Concurrent Collections
(CopyOnWriteArrayList, ConcurrentHashMap).

83. ConcurrentModificationException

 Occurs when a collection is modified while iterating.

 Fail-Fast Iterators → throw exception.

 Fail-Safe Iterators → iterate over a copy, no exception.

 Example Fail-Safe: ConcurrentHashMap, CopyOnWriteArrayList.

84. final, finally, finalize()

 final → keyword (constant, prevent inheritance, prevent overriding).

 finally → block (executes after try-catch, always runs).


 finalize() → method (called by GC before object destruction; deprecated in Java 9+).

85. Autoboxing vs Unboxing

 Autoboxing: converting primitive → wrapper class automatically.

 Integer i = 10; // int → Integer

 Unboxing: converting wrapper → primitive.

 int x = i; // Integer → int

86. Cloneable, Deep vs Shallow Clone

 Cloneable interface allows cloning.

 Shallow Clone: Copies only field values (references are shared).

 Deep Clone: Copies values + referenced objects (true independent copy).

87. Shallow Copy vs Deep Copy

 Shallow Copy: Same references, modifying one affects another.

 Deep Copy: Independent copy, no reference sharing.

Memory Management

88. Java Memory Management

 JVM divides memory into:

o Heap → objects.

o Stack → method calls, local variables.

o Metaspace → class metadata.

 GC handles object cleanup.

89. Garbage Collection in Java

 Automatic memory cleanup of unused objects.

 Types of GC algorithms:

o Serial GC

o Parallel GC

o CMS (Concurrent Mark Sweep)


o G1 (Garbage First, default in Java 9+)

90. finalize() Method

 Called before object destruction by GC.

 Used for cleanup (not recommended).

 Deprecated in modern Java.

91. Stack vs Heap

 Stack

o Stores method calls, local variables.

o Fast, thread-specific.

 Heap

o Stores objects.

o Shared among threads.

92. Handling OutOfMemoryError

 Increase JVM heap size (-Xmx).

 Optimize memory usage (use primitive arrays instead of wrappers).

 Use profiling tools to detect memory leaks.

 Use caching & proper data structures.

Multithreading Basics

93. Multithreading in Java & Lifecycle

 Running multiple threads concurrently.

 Thread lifecycle:

1. New

2. Runnable

3. Running

4. Waiting/Timed Waiting/Blocked

5. Terminated
94. Synchronization

 Used to control access to shared resources.

 Achieved with synchronized keyword.

 Prevents race conditions.

95. wait() vs sleep()

 wait()

o Belongs to Object class.

o Releases lock, waits until notify()/notifyAll().

 sleep()

o Belongs to Thread class.

o Pauses thread but does not release lock.

96. volatile Keyword

 Tells JVM that variable is stored in main memory.

 Ensures visibility across threads.

 Example: volatile boolean flag = true;

97. ThreadLocal

 Provides thread-specific variables.

 Each thread has its own copy.

 Example use case: user session tracking.

98. Deadlock

 Situation where two/more threads are waiting for each other’s lock → infinite wait.

 Avoid by:

o Acquiring locks in fixed order.

o Using tryLock().

o Minimizing synchronized blocks.

99. Thread vs Runnable


 Thread → Extending Thread class.

 Runnable → Implementing Runnable interface.

 ✅ Prefer Runnable (better OOP, avoids multiple inheritance).

100. Runnable vs Callable

 Runnable

o run() method, no return, no checked exception.

 Callable

o call() method, returns a value, can throw exceptions.

 Used with ExecutorService.

101. Synchronized Methods vs Synchronized Blocks

 Synchronized Method

o Locks entire method.

 Synchronized Block

o Locks only specific code section/object.

 ✅ Block is preferred (better performance).

📘 Spring Boot Intermediate – Detailed Answers

102. How does Spring Boot auto-configuration work?

 Spring Boot uses @EnableAutoConfiguration along with [Link] (in older versions) or
AutoConfiguration (in Spring Boot 3+) to automatically configure beans based on:

o Classpath detection (e.g., if spring-boot-starter-data-jpa is present, it auto-


configures DataSource & EntityManager).

o Spring Environment properties (like [Link] or [Link]).

 It reduces boilerplate by providing sensible defaults but allows overriding with custom
beans.

103. What is the role of @Configuration and @Bean?

 @Configuration: Marks a class as a source of bean definitions. Equivalent to XML config in


old Spring.

 @Bean: Used inside a @Configuration class to explicitly declare a bean.


 @Configuration

 public class AppConfig {

 @Bean

 public MyService myService() {

 return new MyService();

 }

 }

 Together they give fine-grained control over bean creation.

104. How do profiles work in Spring Boot (@Profile use case)?

 Profiles allow environment-specific beans/configs.

 Use @Profile("dev"), @Profile("prod") to load beans conditionally.

 Activate profiles with:

o [Link] → [Link]=dev

o CLI → --[Link]=prod

 Example:

 @Profile("dev")

 @Bean

 public DataSource devDataSource() { ... }

105. What is @Transactional, and what's the benefit?

 @Transactional manages database transactions.

 Benefits:

o Automatic commit/rollback.

o Ensures ACID properties.

o Reduces boilerplate (try-catch-finally).

 Example:

 @Transactional

 public void transferMoney(Account from, Account to, double amount) {

 [Link](amount);

 [Link](amount);
 }

106. How do you write a global exception handler in Spring Boot?

 Use @ControllerAdvice + @ExceptionHandler.

 @ControllerAdvice

 public class GlobalExceptionHandler {

 @ExceptionHandler([Link])

 public ResponseEntity<String> handleException(Exception ex) {

 return
[Link](HttpStatus.INTERNAL_SERVER_ERROR).body([Link]());

 }

 }

107. Difference between [Link] and [Link]?

 Both used for configuration.

 Properties file: Key-value pair ([Link]=8080).

 YAML: Hierarchical, cleaner for nested configs.

 server:

 port: 8080

 servlet:

 context-path: /app

 YAML supports lists and structured configs better.

108. What is the use of CommandLineRunner and ApplicationRunner?

 Both are callback interfaces to run code at startup.

 CommandLineRunner → provides String... args.

 ApplicationRunner → provides ApplicationArguments (structured access).

 @Component

 class MyRunner implements CommandLineRunner {

 public void run(String... args) {

 [Link]("App started!");
 }

 }

109. How does the embedded server (Tomcat) work in Spring Boot?

 Spring Boot uses embedded servlet containers (Tomcat, Jetty, Undertow).

 Starts the server internally (no need to deploy WAR externally).

 Uses [Link]() → boots embedded Tomcat on defined port.

110. How do you override default auto-configurations?

 Define custom beans with the same type → overrides defaults.

 Use @ConditionalOnMissingBean in Spring Boot’s auto-configs.

 Disable a specific auto-config:

 [Link]=[Link]
Configuration

111. How do you handle circular dependencies in Spring Boot?

 Circular dependency = A depends on B and B depends on A.

 Solutions:

1. Use constructor injection carefully (can break circular refs).

2. Use @Lazy on one dependency.

3. Refactor design (introduce a third service).

📘 Dependency Injection (DI)

112. What is constructor injection vs field injection vs setter injection?

 Constructor Injection: Dependencies via constructor.

o Preferred (immutable, testable).

 Field Injection: Directly with @Autowired on fields.

o Less recommended (harder to test, reflection-based).

 Setter Injection: Dependencies injected via setter methods.

o Useful for optional dependencies.


113. What is @Qualifier and @Primary annotation?

 @Qualifier: Resolves ambiguity when multiple beans of same type exist.

 @Autowired

 @Qualifier("bean1")

 private MyService service;

 @Primary: Marks a default bean to be injected when no qualifier is specified.

114. If both @Qualifier and @Primary are used, which one will take precedence?

 @Qualifier takes precedence over @Primary.

 If you specify @Qualifier, it overrides the default bean.

115. How to avoid bean creation failures in dependency injection?

 Use:

o @Primary to resolve conflicts.

o @Qualifier to specify exact beans.

o @Lazy for circular references.

o Optional dependencies with @Autowired(required=false).

116. @Autowired vs @Qualifier

 @Autowired: Injects bean by type (and by name if ambiguity exists).

 @Qualifier: Used with @Autowired to specify exact bean when multiple beans exist.

117. @Primary vs @Qualifier

 @Primary: Declares a default bean to be injected when no qualifier is given.

 @Qualifier: Explicitly selects the bean, overriding @Primary.

 Rule: @Qualifier > @Primary > ByType resolution.

Spring Boot Annotations

123. @ComponentScan vs @EnableAutoConfiguration

 @ComponentScan:
o Used to tell Spring where to look for components (@Component, @Service,
@Repository, @Controller).

o Example:

o @ComponentScan(basePackages = "[Link]")

o Without it, Spring might not find your beans in other packages.

 @EnableAutoConfiguration:

o Enables Spring Boot’s auto-configuration feature, which automatically configures


your app based on dependencies.

o Example:

o @EnableAutoConfiguration

o For instance, if spring-boot-starter-web is present, it auto-configures a Tomcat server


and DispatcherServlet.

👉 In practice, we usually use @SpringBootApplication which combines:

@SpringBootApplication = @Configuration + @ComponentScan + @EnableAutoConfiguration

124. @Configuration vs @Bean

 @Configuration:

o Indicates that a class contains Spring bean definitions.

o Example:

o @Configuration

o public class AppConfig {

o @Bean

o public MyService myService() {

o return new MyServiceImpl();

o }

o }

 @Bean:

o Marks a method inside a @Configuration class that returns a bean to be managed by


Spring’s IoC container.

👉 @Configuration = container of bean definitions.


👉 @Bean = defines the actual bean.
125. @Async vs @Scheduled

 @Async:

o Used for asynchronous method execution (runs in a separate thread).

o Example:

o @Async

o public void sendEmail() {

o // runs asynchronously

o }

o Requires @EnableAsync on a configuration class.

 @Scheduled:

o Used to run a method on a fixed schedule (cron, fixed rate, etc.)

o Example:

o @Scheduled(fixedRate = 5000)

o public void checkStatus() {

o // runs every 5 seconds

o }

o Requires @EnableScheduling.

126. @Cacheable vs @CacheEvict

 @Cacheable:

o Caches the result of a method call.

o Next time the same parameters are passed, the cached value is returned.

o Example:

o @Cacheable("products")

o public Product getProductById(Long id) { ... }

 @CacheEvict:

o Removes entries from the cache when data changes (to keep cache fresh).

o Example:

o @CacheEvict(value = "products", allEntries = true)

o public void updateProduct(Product product) { ... }


Database & JPA Basics

127. What is ORM?

 ORM (Object Relational Mapping) is a technique to map Java objects to database tables
automatically.

 It helps developers interact with the database using Java objects instead of SQL queries.

 Examples: Hibernate, EclipseLink, JPA.

128. What is JPA? Difference between JPA and Hibernate?

 JPA (Java Persistence API):

o A specification (set of rules/interfaces) for object-relational mapping in Java.

o It defines how Java objects map to database tables.

 Hibernate:

o A framework that implements JPA.

o It provides actual classes and methods for database operations.

👉 In short:

 JPA = Specification

 Hibernate = Implementation

129. What is an Entity in JPA?

 An Entity represents a table in the database.

 Each instance of an entity represents a row in that table.

 Example:

 @Entity

 @Table(name = "users")

 public class User {

 @Id

 @GeneratedValue(strategy = [Link])

 private Long id;

 private String name;

 }
130. What are JPA annotations (@Entity, @Id, @GeneratedValue)?

 @Entity: Marks a class as a JPA entity (database table).

 @Id: Marks the primary key field.

 @GeneratedValue: Defines how the primary key is generated (AUTO, IDENTITY, SEQUENCE,
TABLE).

Example:

@Entity

public class Product {

@Id

@GeneratedValue(strategy = [Link])

private Long id;

131. Difference between persist() and merge()?

 persist(entity):

o Makes the entity managed and inserts it into the database.

o Fails if entity already exists.

 merge(entity):

o Copies state of a detached entity into a managed one.

o Either updates existing record or inserts new if not found.

👉 persist() → new entities.


👉 merge() → detached entities.

132. JPA relationships (@OneToMany, @ManyToOne, etc.)

 @OneToOne: One entity is related to exactly one other entity.

 @OneToMany: One entity has multiple related entities.

 @ManyToOne: Many entities relate to one entity.

 @ManyToMany: Both sides have multiple relationships.

Example:

@OneToMany(mappedBy = "department")

private List<Employee> employees;


133. What is JPQL?

 JPQL (Java Persistence Query Language):

o A query language similar to SQL but operates on entity objects instead of tables.

o Example:

o @Query("SELECT u FROM User u WHERE [Link] = :name")

134. Lazy Loading vs Eager Loading

 Lazy Loading:

o Data is loaded on demand when accessed.

o Efficient for performance.

o Example: @OneToMany(fetch = [Link])

 Eager Loading:

o Loads related data immediately with the main entity.

o Example: @ManyToOne(fetch = [Link])

135. Difference between save() and saveAndFlush()

 save():

o Saves entity in persistence context (not immediately committed).

o Actual commit happens when transaction completes.

 saveAndFlush():

o Saves entity and immediately writes it to database (forces flush).

o Useful when you need the changes instantly.

136. In Hibernate, difference between get() and load()

 get():

o Immediately hits the database and returns object or null.

o Example:

o [Link]([Link], id);

 load():

o Returns a proxy without hitting DB immediately.


o When you access a property, then it queries DB.

o Throws ObjectNotFoundException if not found.

Testing Basics

137. What is JUnit? Basic annotations

 JUnit: A testing framework for Java to write unit tests.

 Common annotations:

o @Test → Marks method as test.

o @BeforeEach → Runs before each test.

o @AfterEach → Runs after each test.

o @BeforeAll → Runs once before all tests.

o @AfterAll → Runs once after all tests.

o @Disabled → Skips a test.

Example:

@Test

void testSum() {

assertEquals(5, [Link](2, 3));

138. What is @Mockito? When to use @Mock?

 Mockito: A mocking framework used to test components in isolation.

 @Mock: Creates a mock object (fake implementation).

 @InjectMocks: Injects mocks into the class being tested.

Example:

@Mock

private UserRepository userRepository;

@InjectMocks

private UserService userService;

Used when you want to test logic without calling real database or services.
139. What is the difference between @Mock, @MockBean, and @Spy?

Annotation Defined In Purpose Behavior

Creates a mock object (fake Returns default values (null, 0,


@Mock Mockito
dependency) false) for methods unless stubbed

Spring Boot Adds a Mockito mock to the Spring Replaces real bean with mock for
@MockBean
(Test) ApplicationContext integration tests

Creates a partial mock (wraps a real


@Spy Mockito Calls real methods unless stubbed
object)

Examples:

@Mock

private UserRepository userRepository; // Pure mock

@MockBean

private UserRepository userRepository; // Replaces bean in Spring context

@Spy

private UserService userService = new UserService(); // Partial mock

👉 Use:

 @Mock → pure unit tests (no Spring context)

 @MockBean → Spring Boot tests

 @Spy → when you want real behavior + mocking

140. How do you test REST controllers using MockMvc?

MockMvc allows testing REST controllers without starting the full server.

Setup Example:

@WebMvcTest([Link])

class UserControllerTest {

@Autowired

private MockMvc mockMvc;


@MockBean

private UserService userService;

@Test

void testGetUser() throws Exception {

when([Link](1L)).thenReturn(new User(1L, "John"));

[Link](get("/users/1"))

.andExpect(status().isOk())

.andExpect(jsonPath("$.name").value("John"));

Key Annotations:

 @WebMvcTest → loads only controller layer

 @MockBean → mocks service layer dependencies

 MockMvc → simulates HTTP requests and validates responses

141. What is @SpringBootTest vs @WebMvcTest?

Annotation Loads What? Use Case

Full Spring Context (Controllers, Services, Integration tests (end-to-


@SpringBootTest
Repositories, etc.) end)

@WebMvcTest Only Web Layer (Controllers + MVC components) Controller unit tests

Example:

@SpringBootTest

class AppIntegrationTest { ... }

@WebMvcTest([Link])

class UserControllerTest { ... }

👉 Tip:

 Use @WebMvcTest for lightweight controller testing.


 Use @SpringBootTest for full application behavior testing.

🔐 Security Basics

142. What is Authentication vs Authorization?

Concept Meaning Example

Authentication Verifying who the user is (identity check) Login with username & password

Checking what the user can do (access Admin can delete, user can only
Authorization
control) view

👉 Authentication happens first, then Authorization.

143. What is Spring Security?

 A powerful framework that provides authentication, authorization, and protection against


attacks like CSRF, XSS, and Session Fixation.

 Handles security for:

o Web apps (via filters)

o REST APIs (via JWT, BasicAuth, etc.)

 Uses:

o SecurityFilterChain for config

o Custom UserDetailsService for user authentication

Example Config (Java-based):

@Configuration

@EnableWebSecurity

public class SecurityConfig {

@Bean

public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {

[Link]().disable()

.authorizeHttpRequests()

.requestMatchers("/admin/**").hasRole("ADMIN")

.anyRequest().authenticated()

.and()
.httpBasic();

return [Link]();

144. How do you secure REST APIs using Spring Security?

Steps:

1. Add dependency:

2. <dependency>

3. <groupId>[Link]</groupId>

4. <artifactId>spring-boot-starter-security</artifactId>

5. </dependency>

6. Create a security configuration with roles and paths.

7. Use JWT tokens or BasicAuth for stateless APIs.

8. Protect endpoints:

9. [Link]()

10. .requestMatchers("/api/admin/**").hasRole("ADMIN")

11. .anyRequest().authenticated();

12. Return HTTP codes:

o 401 Unauthorized (no login)

o 403 Forbidden (not enough privileges)

145. What is BasicAuth vs JWT?

Feature Basic Auth JWT (JSON Web Token)

Username & password sent with each request Encoded token containing user
How it works
(Base64) data

State Stateless Stateless

Security Less secure (password sent repeatedly) More secure (signed token)

Modern REST APIs,


Use case Small apps, testing
microservices
Feature Basic Auth JWT (JSON Web Token)

Header Authorization: Bearer


Authorization: Basic <base64>
Example <jwt_token>

👉 JWT tokens are better for distributed, scalable apps.

146. What are HTTP status codes: 401, 403, 404, 500, 502, 503?

Code Meaning Example

401 Unauthorized User not authenticated Missing/invalid token

403 Forbidden User authenticated but not authorized Logged in but lacks admin rights

404 Not Found Resource doesn’t exist Wrong URL

500 Internal Server Error Server-side failure NullPointerException, etc.

502 Bad Gateway Invalid response from upstream server Reverse proxy issue

503 Service Unavailable Server temporarily down or overloaded Maintenance mode

214. What is the difference between monolithic and microservices architecture?

 Monolithic: single deployable application containing UI, business logic, data access. Easier to
develop initially, simple local debugging and transaction handling. But becomes hard to
scale, maintain, and deploy as it grows: long release cycles, tight coupling, large codebase,
single-fault domain.
 Microservices: app split into many small, independently deployable services, each owning its
data and a bounded context. Advantages: independent deployment, tech heterogeneity per
service, small teams owning services, fine-grained scaling, fault isolation. Trade-offs:
increased operational complexity (networking, monitoring, CI/CD), distributed concerns
(consistency, transactions), service discovery, cross-service testing, potential duplications.

 When to use: Monolith for small/simple apps or early-stage MVP. Microservices for complex,
scaling systems with multiple teams and clear bounded contexts.

215. How do microservices communicate with each other?

 Synchronous: HTTP/REST, gRPC — request/response for immediate needs. Pros: simple,


human-readable (REST), or high-performance (gRPC). Cons: increases coupling and latency;
needs timeouts/retries/circuit breakers.

 Asynchronous (recommended for decoupling): message brokers (Kafka, RabbitMQ, AWS


SQS, Pulsar). Producers emit events; consumers react. Pros: resilient, decoupled, better
throughput, eventual consistency patterns. Cons: complexity in guarantees, ordering,
idempotency.

 Patterns & concerns: API Gateway for ingress, service discovery (Eureka/Consul/DNS),
correlation IDs for tracing, structured payloads (JSON/Protobuf), idempotency keys, retry and
backoff, circuit breaker, versioning. Choose sync when you need immediate response; async
when you can tolerate eventual consistency or need high throughput.

216. What is RestTemplate? How to use it?

 Definition: RestTemplate is Spring’s synchronous HTTP client for calling REST services
(blocking). Common methods: getForObject, getForEntity, postForObject, exchange.

 Example usage:

RestTemplate rest = new RestTemplate();

String url = "[Link]

User user = [Link](url, [Link], userId);

 Important notes: RestTemplate is thread-safe but considered legacy; Spring recommends


WebClient (from Spring WebFlux) for non-blocking/reactive calls. Configure timeouts, error
handlers, interceptors (for headers/tracing), and connection pooling (via
HttpComponentsClientHttpRequestFactory or OkHttp3ClientHttpRequestFactory) for
production use. Always handle errors and set sensible timeouts.

217. What is an API Gateway? Why is it used?

 Definition: A single-entry HTTP endpoint that routes client requests to multiple backend
microservices.

 Responsibilities: request routing, load balancing, authentication/authorization, SSL


termination, rate limiting, caching, request/response transformation, protocol translation
(e.g., WebSocket ↔ HTTP), aggregation of multiple service calls into one response, logging,
metrics.

 Benefits: simplifies client (one URL), centralizes cross-cutting concerns, enables coarse-
grained responses and version routing.

 Trade-offs: single point to secure and scale; adds latency and complexity. Examples: Spring
Cloud Gateway, Zuul, Kong, NGINX, AWS API Gateway.

218. What is service discovery?


 Purpose: Microservices need to find each other in dynamic environments (instances scale
up/down, move). Service discovery provides the current network locations.

 Types:
o Client-side discovery: client queries a registry (Eureka/Consul) to get service
instances, then load-balances itself.

o Server-side discovery: client calls a load balancer or API gateway which does
discovery (Kubernetes kube-proxy, cloud load balancers).

 How it works: services register themselves on startup and periodically send heartbeats;
registry provides health status and instance list. Use DNS or HTTP APIs for lookups. Ensure
health checks, TTLs and secure registry access.

219. How do you implement resilience patterns (Retry, Circuit Breaker, Bulkhead)?

 Retry: attempt failed operations again with exponential backoff and jitter. Use only for
idempotent operations or ensure idempotency.

 Circuit Breaker: stop calling a failing service after a threshold of failures; periodically test to
see if it recovered (half-open state). Prevents cascading failures.

 Bulkhead: isolate resources (thread pools, connection pools, CPU quotas) per downstream
service so one slow service doesn’t consume all resources.

 Other patterns: timeouts, fallback responses, rate limiting, backpressure, bulk queues.

 Implementation: use libraries like Resilience4j (lightweight, modular) or older Hystrix (now
deprecated), or built-in Spring Cloud CircuitBreaker. Configure thresholds, sliding windows,
retry limits, and monitor metrics. Test chaos scenarios and tune.

220. What is the Circuit Breaker pattern? Libraries like Hystrix/Resilience4j?

 Pattern: Circuit Breaker protects callers from repeatedly invoking a failing dependency.
States: Closed (normal), Open (fail fast), Half-open (trial calls). When failure rate exceeds
threshold, breaker opens; after a wait time it allows a limited number of trial calls. On
success, it closes. It improves system stability and reduces latency.

 Key parameters: failure threshold, sliding window size, wait duration, permitted trial calls,
fallback.

 Libraries:

o Hystrix (Netflix) — historically popular but in maintenance mode.

o Resilience4j — modern, functional, modular, integrates with Spring Boot


(recommended). Supports CB, retry, rate limiter, bulkhead, time limiter.

o Spring Cloud CircuitBreaker provides abstraction over implementations.

 Best practices: provide fallbacks, monitor breaker metrics, set appropriate timeouts, and
avoid over-aggressive thresholds.

221. How do you implement API rate limiting?


 Algorithms: token bucket (smooth bursts), leaky bucket, fixed window, sliding window
log/counter. Token bucket is commonly used.

 Placement: implement at API Gateway or edge (CDN, load balancer) to protect services. Also
apply per-user, per-API-key, per-IP policies.

 Implementation options: Redis-based counters (fast), in-memory for single instance (not
recommended), cloud-managed rate-limiting (API Gateway features). Use distributed rate-
limiters for multi-node setups.

 Behavior: return HTTP 429 with Retry-After header. Consider quotas (daily/monthly) vs
throttling (per-second). Log and expose rate-limit headers to clients. Graceful degradation
and priority lanes for premium users are common.

222. What happens when one microservice becomes slow? Isolation strategies?

 Problems from slowness: high latency cascades to callers, resource exhaustion, increased
error rates.

 Isolation strategies:

o Timeouts: fail fast rather than wait indefinitely.

o Circuit breaker: stop calling until service recovers.

o Bulkheads: isolate thread pools or resources so other services are unaffected.

o Queueing with backpressure: buffer requests and reject or slow producers.

o Rate limiting & prioritization: protect critical flows.

o Fallbacks / degrade gracefully: provide cached or partial data.

o Autoscaling & health checks: scale slow services and remove unhealthy instances.

 Observability: monitor latency, set alerts and trace incoming requests to root cause.

223. How do you handle versioning of REST APIs?

 Strategies:

o URI versioning: /api/v1/users — explicit and simple.

o Header versioning: Accept header or custom header API-Version. Cleaner URIs but
harder for browsers/tools.

o Media type versioning: application/[Link].v1+json.

o Query param: ?version=1 (less common).

 Backward compatibility: prefer additive changes (adding fields) that don’t break old clients.
For breaking changes, create a new version and deprecate old API with a migration window.
 Other practices: document versions clearly, use API gateway routing by version, use contract
testing (e.g., Pact), semantic versioning for API behavior, and deprecation headers/messages.

224. How do you implement distributed logging and tracing (ELK, Zipkin)?

 Centralized logging: send structured logs (JSON) from services to a log aggregator (ELK/EFK
stack: Elasticsearch, Logstash/Filebeat, Kibana) or hosted SaaS (Datadog, Splunk). Include
metadata: service, instance id, timestamp, correlation id, level, user id.

 Distributed tracing: instrument services with tracing libraries (OpenTelemetry, Zipkin,


Jaeger). Propagate trace and span IDs in request headers (traceparent/X-B3-TraceId) across
sync/async calls. Use spans to measure latency breakdown and find bottlenecks.

 Correlation: use correlation IDs (one per incoming client request) to tie logs and traces
together.

 Best practices: sample traces to reduce cost, capture errors and slow traces, use dashboards
and alerting, redact sensitive data, and ensure log retention policy.

225. What's the difference between sync and async communication?

 Synchronous: caller waits (blocks) for response. Simpler control flow and error handling, but
increases latency and coupling. Example: REST/gRPC request-reply.

 Asynchronous: caller sends message/event and returns immediately; processing happens


later. Better decoupling, higher throughput, resilience to temporary failures. Example: events
via Kafka or message queues.

 Trade-offs: sync easier for immediate result; async requires eventual consistency handling,
more complex error/retry patterns, requires durable storage and idempotency. Choose
based on SLA, coupling, and data consistency requirements.

226. What is eventual consistency? CAP theorem?


 CAP theorem: in presence of network Partition (P), you must choose between Consistency (C
— all nodes see same data) or Availability (A — every request receives a response). You
cannot guarantee all three simultaneously in a distributed system.

 Eventual consistency: systems accept temporary inconsistencies and guarantee that, given
no new updates, all replicas will converge to the same state eventually. Useful for high
availability and partition tolerance.
 Patterns: use conflict resolution (last-write-wins, version vectors), CRDTs, or explicit
reconciliations. Understand when strong consistency (transactions) is required vs eventual
consistency (user feeds, materialized views).

227. How do you implement Saga pattern for distributed transactions?


 Purpose: coordinate multi-service business transactions without 2PC. Sagas model a
workflow composed of local transactions; if one step fails, execute compensating
transactions to undo prior steps.

 Approaches:

o Choreography: each service emits events; downstream services react. Simple wiring
but harder to observe and debug.

o Orchestration: a central orchestrator (Saga manager) sends commands to


participants and handles success/failure/compensation. Easier to monitor and
reason about.

 Key concerns: idempotency of steps and compensations, ordering, retries, timeouts,


persistent saga state (store progress), failure handling, auditability. Tools include custom
orchestrators or frameworks (e.g., Temporal, Camunda, or home-grown saga managers). Test
compensating flows thoroughly.

228. How do you handle data consistency across microservices?

 Options & patterns:

o Saga & compensating transactions for business workflows.


o Event sourcing: state changes stored as events; services rebuild state from event
streams. Good for audit and eventual consistency.

o CQRS: separate read/write models; write side emits events used to update read
models asynchronously.

o Change Data Capture (CDC): capture DB changes and publish to message bus for
syncing other services.

o Anti-corruption layer: when integrating legacy systems, build translation layers to


protect your domain.

 Practices: accept that duplication is common (each service owns its data), design for
eventual consistency, use idempotent consumers, implement reconciliation jobs, and decide
consistency boundaries based on business needs.

229. Microservices architecture vs Monolithic architecture


(Short summary complementing Q214)

 Microservices: distributed, autonomous services, independent deploys, better per-service


scaling, suitable for large teams/complex domains. More operational overhead (CI/CD,
monitoring, networking), more complex testing and consistency handling.

 Monolithic: single deployable process, simpler to develop/operate initially, easier local


debugging and transactions. Can become slower to change as it grows.
 Decision factors: team size, complexity, release velocity needs, operational maturity, and
business domain boundaries.

230. What is producer and consumer applications?

 Producer: an application or service that creates and sends messages/events to a messaging


system (topic/queue). Example: Order Service publishes OrderCreated events.

 Consumer: an application that receives and processes those messages. Example: Inventory
Service consumes OrderCreated to reserve stock.

 Patterns: publish–subscribe (fan-out to multiple consumers) vs work queues (competing


consumers for load balancing). Consider message semantics: at-most-once, at-least-once,
exactly-once (hard). Implement idempotency, acknowledgements, dead-letter queues (DLQ)
for failures, and monitor consumer lag (for Kafka) and throughput.

283. How do you profile Java applications?

Purpose: Identify performance bottlenecks (CPU, memory, threads, I/O).


Approaches:

 Sampling profilers: periodically capture stack traces (less overhead).

o Tools: VisualVM, JProfiler, YourKit, Java Flight Recorder (JFR), async-profiler.

 Instrumentation profilers: measure method execution times precisely (more overhead).

o Example: JProfiler or Java Agent with bytecode instrumentation.

 Steps:

1. Run application with profiling agent.

2. Record CPU/memory usage under real load.

3. Inspect hot methods, GC activity, object allocations, thread states.

4. Optimize top offenders (e.g., inefficient loops, blocking I/O, excessive GC).

 Best practices: profile in a similar environment to production, use sampling mode first, and
repeat after each optimization.

284. How to debug memory leaks?

Symptoms: OutOfMemoryError, GC taking too long, increasing heap usage, degraded performance.
Steps to diagnose:

1. Enable GC logging:

2. -Xlog:gc*:[Link]
Look for high GC frequency and low reclaimed memory.

3. Capture a heap dump:

4. jmap -dump:live,format=b,file=[Link] <pid>

5. Analyze heap dump: use Eclipse MAT, VisualVM, JProfiler, or YourKit.

o Check dominators tree and retained size for large object graphs.

o Identify static collections or caches that keep growing.

6. Fix leaks:

o Close streams, ResultSets, Sessions.

o Remove unbounded caches or use weak references.

o Deregister JDBC drivers, listeners, threads in shutdown.

7. Prevention: enable monitoring, review lifecycle of beans, and use tools like LeakCanary (for
Android) or VisualVM in dev.

285. How to analyze thread dumps?

Purpose: Diagnose deadlocks, thread contention, or stuck threads.


Steps:

1. Generate thread dump:

2. jstack <pid> > [Link]

3. Analyze:

o Look for threads in BLOCKED or WAITING state.

o Check stack traces for contention points (e.g., synchronized, locks, DB calls).

o Identify deadlocks (at the bottom of the dump).

o Review high CPU threads with:

o top -H -p <pid> # find thread id using most CPU

o printf "%x\n" <tid> # convert to hex, match with thread dump

4. Tools: [Link], Samurai, VisualVM thread analyzer, TDA (Thread Dump Analyzer).

5. Fixes: avoid synchronized bottlenecks, use concurrent collections, add timeouts to locks,
offload I/O to async.

286. Gateway Timeout (504) vs Service Unavailable (503) – troubleshooting


Code Meaning Common Causes Fix

Tune timeout configs (API


Gateway didn’t receive Slow downstream,
504 Gateway Gateway, load balancer),
response in time from backend network delay,
Timeout optimize backend
service overloaded backend
performance

Service down, Check service health, scaling,


503 Service Service temporarily
deploying, circuit restart, fix failing
Unavailable unavailable/unhealthy
breaker open, scaling dependencies

Steps:

1. Check gateway and service logs.

2. Identify whether service was reachable.

3. Verify timeouts (client → gateway → service).

4. Correlate with APM traces to find slow components.

287. How do you optimize database queries?

Techniques:

1. Use indexes wisely (on WHERE, JOIN, ORDER BY columns). Avoid too many.

2. Analyze query plan: EXPLAIN (MySQL/PostgreSQL) → detect full scans, missing indexes.

3. Use pagination (LIMIT/OFFSET) instead of fetching all rows.

4. Avoid **SELECT ***; fetch only needed columns.

5. Batch inserts/updates instead of one-by-one.

6. Use connection pooling (HikariCP).

7. Optimize joins and subqueries; consider denormalization for heavy reads.

8. Cache frequent reads (Redis).

9. Monitor slow queries with database logs or APM.

10. Always measure performance before and after change.

288. How to handle high CPU usage in production?

Steps:

1. Identify process: top, htop, or monitoring dashboard.

2. Find high-CPU threads:

3. top -H -p <pid>
4. Map thread to stack trace:
Convert thread ID to hex and match in jstack output.

5. Common causes:

o Infinite loops or heavy computation.

o Excessive GC activity.

o High contention (spin-locking).

o Busy waiting or tight retry loops.

6. Fixes:

o Optimize loops, caching, I/O operations.

o Tune GC (G1GC, heap size).

o Profile CPU hot methods using VisualVM/JFR.

o Offload CPU-intensive tasks to background workers or async.

7. Prevent: load test before release, alert on CPU spikes.

289. What tools do you use for application monitoring?

Common categories:

 APM (Application Performance Monitoring):


New Relic, AppDynamics, Datadog, Dynatrace, Elastic APM, Prometheus + Grafana.

 Metrics collection: Micrometer (Spring Boot), Prometheus exporters, JMX exporters.

 Logs: ELK stack (Elasticsearch, Logstash, Kibana), EFK (Fluentd), Loki + Grafana.

 Tracing: Zipkin, Jaeger, OpenTelemetry.

 Health checks: Spring Boot Actuator, Kubernetes liveness/readiness probes.

 Dashboards: Grafana, Kibana.


Best practices:

o Use distributed tracing IDs.

o Centralize logs and metrics.

o Set up alerting for SLA breaches (latency, error rate, memory).

290. How do you implement distributed tracing?

Purpose: Trace a request end-to-end across multiple microservices.


Implementation steps:
1. Instrument code: use OpenTelemetry or Spring Cloud Sleuth to add trace/span IDs
automatically.

2. Propagate headers:

3. traceparent / X-B3-TraceId / X-B3-SpanId

across all HTTP/gRPC calls.

4. Exporter setup: send traces to Zipkin, Jaeger, or Grafana Tempo.

5. Visualization: view spans timeline (where latency occurs).

6. Integrations: APM tools like Datadog or New Relic can automatically collect traces.

7. Best practices:

o Tag spans with metadata (user ID, endpoint).

o Sample wisely to avoid overhead.

o Correlate with logs using trace IDs.

291. Service Not Found – how to troubleshoot?

Possible causes:

 Wrong service name or endpoint (DNS/registry misconfiguration).

 Service not registered in Eureka/Consul.

 Deployment failed or instance unhealthy.

 Network/firewall issue.

 API Gateway misrouting or wrong base path.


Steps:

1. Verify service registration and health check.

2. Try direct access (curl / Postman).

3. Check gateway routing rules.

4. Check logs for exceptions (UnknownHostException, 404, 503).

5. Validate environment config ([Link], base URL).

6. Redeploy or restart if needed.

7. Use distributed tracing to confirm request path.

292. How to debug locally & remotely?

Local Debugging:
 Use IDE (IntelliJ, Eclipse) with debug mode (Run → Debug).

 Add breakpoints and inspect variables.

 Use logs and mock dependencies (e.g., MockMvc, WireMock).

 Start Spring Boot with debug flags:

 mvn spring-boot:run -[Link]=dev

Remote Debugging:

1. Start app with JVM debug agent:

2. java -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:5005 -jar [Link]

3. In IDE, create “Remote Debug” configuration → connect via host:5005.

4. Use SSH tunnel if in cloud (ssh -L 5005:localhost:5005 user@server).

5. For containers: expose port 5005 in Docker/Kubernetes.

6. Always disable remote debugging in production (security risk).

307. Spring Boot starts 45s in production but 5s locally — how to investigate?

Possible causes

 Different profiles/config (heavy auto-configurations, extra beans, health checks).

 Waiting on network I/O (DB, remote config server, LDAP, NTP, DNS).

 Container/VM resource limits (CPU, slow disk).

 JVM differences (GC, flags, version), classpath/resource scanning, AOT vs JAR layout.

 Large static initialization or @PostConstruct calls.

Investigation steps

1. Compare startup logs (--debug / spring-boot:run) between local and prod — look for long
gaps.

2. Enable actuator startup//actuator/health and Spring Boot autoconfiguration report.

3. Use jcmd/jstack/jstat/GC logs to spot pauses; enable verbose GC.

4. Check network timeouts: try telnet/curl to external services from prod host during startup.

5. Check container limits (cgroups) and CPU throttling.

6. Temporarily disable heavy beans / external connections to isolate.

Fixes
 Lazy-init beans, defer heavy work, make external calls asynchronous or with timeouts.

 Tune JVM and GC, provide adequate CPU/memory, use lighter profiles in prod for startup.

 Pre-warm caches or warm-up endpoints.

308. REST APIs responding in 5+ seconds after deploy — debugging approach?

Investigation

1. Reproduce: check timestamps, logs, metrics for p50/p95/p99 latency.

2. Distributed tracing (Zipkin/Jaeger) to see which layer is slow.

3. Check DB slow queries (EXPLAIN), connection pool exhaustion, thread pool saturation.

4. CPU/GPU/GC profiling, thread dumps during slowness.

5. Look for external dependency latency (auth, payment, third-party APIs).

6. Check recent deploy changes (new library, heavy serialization).

Fixes

 Add caching (Redis / HTTP cache) for expensive calls.

 Optimize DB (indexes, query rewrite) and use pagination.

 Tune connection pools, thread pools, increase timeouts and add retries with backoff.

 Use async processing / background jobs for non-blocking work.

 Introduce circuit breakers, bulkheads, and rate-limiting.

309. Works for 100 users but crashes OOM at 1000 users — solution?

Likely causes

 Memory leaks (unreleased references, static caches).

 Unbounded in-memory caches or queues.

 Too many threads / per-request large object allocation.

 Keeping large session objects in JVM (HTTP session storage).

How to solve

1. Capture heap dump at OOM (-XX:+HeapDumpOnOutOfMemoryError) and analyze with


Eclipse MAT.

2. Check GC logs to see memory growth pattern and frequency.

3. Identify leaking objects, large collections or ephemeral objects retained.

4. Limit cache sizes; use bounded caches (Caffeine) with eviction policies.
5. Move sessions off-heap (Redis/session store) or make app stateless.

6. Tune thread pools and connection pools; add backpressure or rate-limits.

7. Horizontal scale (more instances behind LB) and autoscaling.

310. Microservice occasionally returns 503 during peak — possible causes?

Causes

 Overload: thread/connection pool exhaustion.

 Upstream dependency failures or timeouts.

 Pod/container restarts due to OOM/health probe failing.

 Load balancer marking instances unhealthy (readiness probe).

 Rate limiting or circuit-breaker open state.

Mitigations

 Autoscale based on CPU/latency; right-size resources.

 Tune thread pools, DB connections; use bulkheads.

 Implement retries with backoff, circuit breakers, graceful degradation.

 Ensure health/readiness probes are correct and not too strict.

 Add caching & queueing to smooth bursts.

311. Users logged out every 30 minutes though JWT valid 24 hours — what’s happening?

Possible reasons

 Cookie/session expiry shorter than JWT expiry (cookie max-age or expires set to 30 min).

 Server-side session or token revocation logic clearing sessions.

 Refresh token or token rotation policy revokes old tokens.

 Clock skew / TTL in cache (Redis) that stores user session metadata.

 Load balancer or multiple IDP keys causing token validation failures after key rotation.

Fix

 Inspect the token exp and cookie attributes (SameSite, Secure, Max-Age).

 Check any server-side session store or token invalidation code.

 Verify system clocks (NTP) and key rotation policy.

 If truly stateless JWT desired, avoid server-session logic or provide a consistent validation
store.
312. API hit by 10,000 req/s from same IP — rate limiting approach?

Approaches

 Edge/Network level: Use CDN/WAF (Cloudflare, AWS Shield) and IP blocking for DDoS.

 API Gateway: Kong/Envoy/Nginx/ALB throttle per IP/client id.

 Algorithm: Token bucket or leaky bucket; fixed-window or sliding window counters.

 Distributed store: Implement counters in Redis (INCR + EXPIRE or Lua script for token
bucket).

 Responses: Return 429 Too Many Requests with Retry-After.

 Further steps: CAPTCHA, require API key with quotas, progressive throttling, blacklisting, and
monitoring/alerts.

313. Implement SSO for 20 apps — design?

High-level design

 Use a centralized Identity Provider (IdP) supporting OAuth2 / OpenID Connect (Keycloak,
Auth0, Azure AD) or SAML if needed.

 Each application becomes an OAuth/OIDC client that delegates auth to IdP.

 Use standard flows (Authorization Code + PKCE for SPAs) and consistent session/cookie
domain for SSO.

 User provisioning via SCIM, central user store (LDAP/AD or managed DB).

 Implement single logout (front-channel/back-channel), token revocation, and refresh tokens.

 Add MFA, role-based access control, and logging/audit.

 Provide SDKs or libraries for apps to integrate and handle token renewal securely.

Considerations

 Cross-domain cookies, security (CSRF, secure cookies), session expiry and refresh strategies,
and multi-tenant isolation if needed.

314. E-commerce app takes 30s to load 10,000 product catalog — how to optimize?

Strategies

 Don’t load all 10k at once: use pagination or lazy loading (infinite scroll).

 Use DB-level optimizations: proper indexes, selective columns, avoid N+1.

 Use search engine (Elasticsearch) for catalog/filters.


 Cache results (Redis) and use CDN for static assets (images).

 Precompute aggregations/materialized views for frequent queries.

 Return compact DTOs (no large image blobs), compress responses, and use streaming where
possible.

 Database connection pooling and query tuning.

315. LazyInitializationException in production but not in tests — why & fix?

Cause

 Entity graph is accessed after Hibernate session is closed (detached entity). Tests may use
@Transactional or OpenSessionInView but prod code path doesn’t.

 Different fetch strategy or transaction boundaries between test and prod.

Fixes

 Initialize needed lazy associations inside transactional service layer (e.g., fetch joins JOIN
FETCH).

 Use DTO projections (select into DTO) so you fetch exactly what you need.

 Consider @Transactional on service methods that prepare data for view.

 If appropriate, enable OpenSessionInView (careful of N+1).

 Use EntityGraph or [Link]() where required.

316. Two users try to update same product simultaneously — how to handle?

Options

 Optimistic locking: Add version column and let DB/Hibernate detect conflicts; on conflict
return error and ask client to retry/merge. (Preferred for most web apps.)

 Pessimistic locking: SELECT ... FOR UPDATE when strong consistency needed (avoid for high
concurrency).

 Application-level: Use compare-and-swap updates, idempotency tokens, or accept last-


write-wins if business allows.

 UI/UX: Show conflict info to user and allow manual merge or show “stale” warning.

 Event sourcing / CQRS: For complex domains, use event-driven commands and sequence
guarantees.

Desgin patterns
🎯 What Are Design Patterns?

Definition (simple way to say in interview):

“Design patterns are proven and reusable solutions to common software design problems. They
represent best practices used by experienced developers to design flexible, maintainable, and
scalable software.”

They help you write cleaner, well-structured, and reusable code.

💡 How to Answer in an Interview

When asked “What are Design Patterns?”, your answer can be like:

“Design patterns are standard solutions to recurring design problems in software development.
They’re not specific to Java but widely used in object-oriented programming.
In Java, they help make the code more maintainable, flexible, and easier to understand.”

Then you can add an example, like:

“For example, the Singleton Pattern ensures that only one instance of a class is created throughout
the application — it’s often used for things like database connections or logging.”

🧱 Types of Design Patterns

There are 23 official design patterns, grouped into 3 main categories:

Category Purpose Example Patterns

Object creation mechanism, trying to


1. Creational Singleton, Factory Method, Abstract
create objects in a manner suitable to the
Patterns Factory, Builder, Prototype
situation

2. Structural Deal with class and object composition — Adapter, Bridge, Composite, Decorator,
Patterns how objects work together Facade, Flyweight, Proxy

Observer, Strategy, Command, Iterator,


3. Behavioral
Handle communication between objects State, Template Method, Chain of
Patterns
Responsibility

🧱 Most Common Java Examples (with short 1-line use)

Pattern Purpose Example use

Singleton Only one instance of a class Database connection


Pattern Purpose Example use

Factory Create objects without exposing creation


ShapeFactory that creates Circle, Square
Method logic

Builder Construct complex objects step by step StringBuilder, PizzaBuilder

Observer One-to-many dependency Event handling in GUI, or Listener in Java

Define multiple algorithms and choose


Strategy Payment methods (CreditCard, PayPal)
one at runtime

I/O streams (BufferedReader,


Decorator Add new behavior dynamically
InputStreamReader)

Facade Simplify complex subsystem [Link] hides networking details

🗣️ Example Interview Answer (Full Form)

“Design patterns are reusable templates that solve common problems in software design.
They make the code more maintainable and flexible.
For example, Java’s Singleton pattern ensures that only one instance of a class is created — it’s
commonly used for database connections.
There are three main categories: Creational, Structural, and Behavioral patterns.
Some examples are Factory (object creation), Observer (event notification), and Decorator (adding
functionality dynamically).”

⚙️ How to Prepare Practically

✅ Understand 1–2 patterns deeply in each category


✅ Be ready to explain with a small code example or real-world analogy
✅ Example:

 Singleton: “Like having only one printer manager in a system.”

 Observer: “Like YouTube notifications — one change (new video) notifies many subscribers.”

🧱 Technical Leadership

320. How do you evaluate new technologies for adoption?

I start by identifying the problem we’re trying to solve — not adopting tech just because it’s trendy. I
then compare possible technologies on performance, scalability, community support, and integration
with our current stack.
I usually run small proof-of-concept projects, evaluate developer learning curves, and gather
feedback from the team before finalizing adoption. For example, before introducing Spring Boot for
microservices, I first compared it with Micronaut and Quarkus in terms of startup time and ease of
integration.

321. Describe your approach to technical debt management.

I treat technical debt as part of the project lifecycle. I document it, quantify its impact, and prioritize
it based on risk.
During sprint planning, I allocate a small percentage (around 10–15%) of capacity to address high-
impact technical debt items. I also promote clean code practices, code reviews, and automated tests
to prevent unnecessary accumulation.
This approach ensures our system remains maintainable without slowing down feature delivery.

322. How do you handle disagreements in technical design?


I start by understanding each person’s reasoning — usually disagreements come from different
perspectives or priorities. I organize a short technical discussion focusing on facts, data, and long-
term scalability instead of opinions.
If needed, I prototype both options or use benchmarks to guide the decision.
The key is keeping communication respectful and objective, ensuring everyone feels heard.

323. What's your strategy for mentoring junior developers?

I start by understanding their strengths and areas for growth. Then I assign tasks that challenge them
slightly beyond their comfort zone but are achievable with guidance.
I conduct regular code reviews, give actionable feedback, and explain not just what to fix but why.
I also encourage them to read project documentation, explore design patterns, and build small side
projects to improve their confidence.

⚙️ Problem Solving

324. Describe a complex technical problem you solved.

In one project, we faced performance issues in our Java-based banking app due to inefficient SQL
queries. I profiled the code using JProfiler, identified bottlenecks, and replaced multiple N+1 queries
with optimized joins and pagination.
This reduced API response time from 5 seconds to under 1 second and improved overall scalability.

325. How did your technical decisions impact business metrics?

When I implemented Redis caching for frequently accessed data, it reduced database load by 40%
and improved user response time significantly.
This decision directly improved user retention and decreased server costs, which reflected positively
in the business KPIs.

326. Describe a time you prevented a major production issue.

During a deployment, I noticed our new logging configuration could expose sensitive user data.
Before release, I implemented data masking in logs and added validation checks in CI/CD.
This proactive step prevented a potential data leak and ensured compliance with security policies.

327. How do you prioritize technical improvements vs new features?


I balance business goals with technical health. I use three factors: impact, risk, and effort.
If a technical improvement directly affects system reliability or developer productivity, I prioritize it.
Otherwise, I plan it in upcoming sprints along with new features.
I discuss trade-offs transparently with product owners to maintain both short-term delivery and long-
term sustainability.

💬 Communication & Collaboration

328. How do you explain technical concepts to non-technical stakeholders?

I simplify technical terms using analogies and focus on business value rather than implementation.
For example, instead of saying “We need to refactor for dependency injection,” I say, “We’ll make the
system easier to update in the future, reducing maintenance time.”
This helps stakeholders make informed decisions without being overwhelmed by jargon.

329. Describe a time you had to work with a difficult team member.
I once worked with a teammate who resisted code reviews. Instead of confronting directly, I
scheduled a one-on-one to understand their concerns.
Turns out they felt reviews slowed them down, so I proposed lighter reviews for small changes and
collaborative reviews for complex ones.
That built trust and improved our workflow without conflict.

330. How do you handle pressure and tight deadlines?

I stay calm and break tasks into smaller deliverables. I prioritize based on critical impact and
communicate early if risks arise.
I also automate repetitive tasks and focus on team coordination.
During high-pressure releases, I rely on clear checklists and version control to avoid mistakes.
The key is maintaining quality under pressure, not just speed.

You might also like