# Java Interview Questions & Answers - 1 Year Experience
## Table of Contents
1. [Core Java Fundamentals](#core-java-fundamentals)
2. [Object-Oriented Programming](#object-oriented-programming)
3. [Collections Framework](#collections-framework)
4. [Exception Handling](#exception-handling)
5. [Multithreading](#multithreading)
6. [String Handling](#string-handling)
7. [Java 8+ Features](#java-8-features)
8. [Memory Management](#memory-management)
9. [Design Patterns](#design-patterns)
10. [JDBC & Database](#jdbc--database)
11. [Spring Framework Basics](#spring-framework-basics)
12. [Coding Questions](#coding-questions)
---
## Core Java Fundamentals
### 1. What is Java and what are its key features?
**Answer:** Java is a high-level, object-oriented programming language developed by
Sun Microsystems (now Oracle). Key features include:
- **Platform Independence**: "Write once, run anywhere" through JVM
- **Object-Oriented**: Supports encapsulation, inheritance, polymorphism,
abstraction
- **Automatic Memory Management**: Garbage collection handles memory
allocation/deallocation
- **Multithreading**: Built-in support for concurrent programming
- **Security**: Strong security features with bytecode verification
- **Robustness**: Strong type checking, exception handling
### 2. Explain the difference between JDK, JRE, and JVM.
**Answer:**
- **JVM (Java Virtual Machine)**: Runtime environment that executes Java bytecode.
Platform-specific.
- **JRE (Java Runtime Environment)**: JVM + standard libraries needed to run Java
applications
- **JDK (Java Development Kit)**: JRE + development tools (compiler, debugger,
etc.)
### 3. What are the primitive data types in Java?
**Answer:** Java has 8 primitive data types:
- **byte**: 8-bit signed integer (-128 to 127)
- **short**: 16-bit signed integer (-32,768 to 32,767)
- **int**: 32-bit signed integer (-2³¹ to 2³¹-1)
- **long**: 64-bit signed integer (-2⁶³ to 2⁶³-1)
- **float**: 32-bit floating point
- **double**: 64-bit floating point
- **char**: 16-bit Unicode character
- **boolean**: true or false
### 4. What is the difference between == and equals() method?
**Answer:**
- **==**: Compares references (memory addresses) for objects, values for primitives
- **equals()**: Compares actual content/values of objects (must be overridden for
custom comparison)
```java
String s1 = new String("hello");
String s2 = new String("hello");
System.out.println(s1 == s2); // false (different references)
System.out.println(s1.equals(s2)); // true (same content)
```
### 5. What is autoboxing and unboxing?
**Answer:**
- **Autoboxing**: Automatic conversion of primitive types to their wrapper classes
- **Unboxing**: Automatic conversion of wrapper classes to primitive types
```java
Integer i = 5; // Autoboxing (int to Integer)
int j = new Integer(10); // Unboxing (Integer to int)
```
### 6. What are wrapper classes?
**Answer:** Wrapper classes provide object representation of primitive types:
- byte → Byte
- short → Short
- int → Integer
- long → Long
- float → Float
- double → Double
- char → Character
- boolean → Boolean
### 7. What is the difference between String, StringBuffer, and StringBuilder?
**Answer:**
- **String**: Immutable, thread-safe, new object created for each modification
- **StringBuffer**: Mutable, thread-safe (synchronized), better for multi-threaded
environments
- **StringBuilder**: Mutable, not thread-safe, better performance in single-
threaded environments
### 8. What are access modifiers in Java?
**Answer:**
- **public**: Accessible from anywhere
- **protected**: Accessible within package and subclasses
- **default (package-private)**: Accessible within same package
- **private**: Accessible only within the same class
### 9. What is the difference between static and non-static methods?
**Answer:**
- **Static methods**: Belong to class, called without object creation, cannot
access instance variables
- **Non-static methods**: Belong to instance, require object creation, can access
both static and instance variables
### 10. What is method overloading?
**Answer:** Having multiple methods with the same name but different parameters
(number, type, or order). Compile-time polymorphism.
```java
public void print(int a) { }
public void print(String s) { }
public void print(int a, String s) { }
```
---
## Object-Oriented Programming
### 11. What are the four pillars of OOP?
**Answer:**
1. **Encapsulation**: Bundling data and methods together, hiding internal
implementation
2. **Inheritance**: Creating new classes based on existing classes
3. **Polymorphism**: Same interface, different implementations
4. **Abstraction**: Hiding complex implementation details, showing only essential
features
### 12. What is inheritance and what are its types?
**Answer:** Inheritance allows a class to inherit properties and methods from
another class.
**Types:**
- **Single**: Class inherits from one parent class
- **Multilevel**: Chain of inheritance (A→B→C)
- **Hierarchical**: Multiple classes inherit from one parent
- **Multiple**: Not supported in Java (but achieved through interfaces)
### 13. What is method overriding?
**Answer:** Redefining a parent class method in child class with same signature.
Runtime polymorphism.
```java
class Animal {
public void sound() { System.out.println("Animal makes sound"); }
}
class Dog extends Animal {
@Override
public void sound() { System.out.println("Dog barks"); }
}
```
### 14. What is the difference between overloading and overriding?
**Answer:**
| Overloading | Overriding |
|-------------|------------|
| Same class | Different classes (inheritance) |
| Same method name, different parameters | Same method signature |
| Compile-time polymorphism | Runtime polymorphism |
| Can have different return types | Must have same return type |
### 15. What is an abstract class?
**Answer:** A class declared with `abstract` keyword that cannot be instantiated.
Can contain:
- Abstract methods (without implementation)
- Concrete methods (with implementation)
- Variables and constructors
```java
abstract class Shape {
abstract void draw();
void commonMethod() { System.out.println("Common functionality"); }
}
```
### 16. What is an interface?
**Answer:** A contract that defines what methods a class must implement. All
methods are implicitly public and abstract (before Java 8).
```java
interface Drawable {
void draw();
default void print() { System.out.println("Printing..."); } // Java 8+
}
```
### 17. What is the difference between abstract class and interface?
**Answer:**
| Abstract Class | Interface |
|----------------|-----------|
| Can have concrete methods | All methods abstract (pre-Java 8) |
| Can have constructors | Cannot have constructors |
| Can have instance variables | Only static final variables |
| Single inheritance | Multiple inheritance |
| Can have access modifiers | Methods are public by default |
### 18. What is polymorphism?
**Answer:** Ability of objects to take multiple forms. Two types:
- **Compile-time**: Method overloading
- **Runtime**: Method overriding
```java
Animal animal = new Dog(); // Reference of parent, object of child
animal.sound(); // Calls Dog's sound method
```
### 19. What is encapsulation?
**Answer:** Wrapping data and methods into a single unit (class) and restricting
direct access to some components. Achieved through:
- Private variables
- Public getter/setter methods
```java
class Student {
private String name;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
}
```
### 20. What is constructor chaining?
**Answer:** Calling one constructor from another using `this()` or `super()`.
```java
class Student {
private String name;
private int age;
public Student() {
this("Unknown", 0); // Calls parameterized constructor
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
}
```
---
## Collections Framework
### 21. What is the Collections Framework in Java?
**Answer:** A unified architecture for representing and manipulating collections.
Provides:
- **Interfaces**: List, Set, Map, Queue
- **Implementations**: ArrayList, LinkedList, HashMap, TreeMap, etc.
- **Algorithms**: Sorting, searching, shuffling
### 22. What is the difference between Collection and Collections?
**Answer:**
- **Collection**: Root interface of collection framework
- **Collections**: Utility class with static methods for collection operations
### 23. What is the difference between ArrayList and LinkedList?
**Answer:**
| ArrayList | LinkedList |
|-----------|------------|
| Dynamic array implementation | Doubly linked list implementation |
| Random access O(1) | Sequential access O(n) |
| Insertion/deletion O(n) | Insertion/deletion O(1) |
| Better for frequent access | Better for frequent modifications |
| Less memory overhead | More memory overhead (node pointers) |
### 24. What is the difference between Array and ArrayList?
**Answer:**
| Array | ArrayList |
|-------|-----------|
| Fixed size | Dynamic size |
| Can store primitives | Stores objects only |
| Better performance | Slightly slower due to boxing |
| No built-in methods | Rich set of methods |
### 25. What is the difference between HashMap and Hashtable?
**Answer:**
| HashMap | Hashtable |
|---------|-----------|
| Not synchronized (not thread-safe) | Synchronized (thread-safe) |
| Allows null key and values | Doesn't allow null key or values |
| Better performance | Slower due to synchronization |
| Introduced in Java 1.2 | Legacy class from Java 1.0 |
### 26. What is the difference between HashSet and TreeSet?
**Answer:**
| HashSet | TreeSet |
|---------|---------|
| Hash table implementation | Red-Black tree implementation |
| No ordering | Sorted order |
| O(1) operations | O(log n) operations |
| Allows null values | Doesn't allow null values |
| Better performance | Slower but maintains order |
### 27. What is the difference between Comparable and Comparator?
**Answer:**
- **Comparable**: Interface implemented by class itself, defines natural ordering
- **Comparator**: Separate class that defines custom ordering logic
```java
// Comparable
class Student implements Comparable<Student> {
public int compareTo(Student s) { return this.name.compareTo(s.name); }
}
// Comparator
Comparator<Student> byAge = (s1, s2) -> Integer.compare(s1.age, s2.age);
```
### 28. What is the difference between Iterator and ListIterator?
**Answer:**
| Iterator | ListIterator |
|----------|--------------|
| Forward direction only | Bidirectional |
| Works with all collections | Only for List implementations |
| hasNext(), next(), remove() | Additional: hasPrevious(), previous(), add(), set()
|
### 29. What is the difference between fail-fast and fail-safe iterators?
**Answer:**
- **Fail-fast**: Throws ConcurrentModificationException if collection is modified
during iteration (ArrayList, HashMap)
- **Fail-safe**: Creates copy of collection, doesn't throw exception
(ConcurrentHashMap, CopyOnWriteArrayList)
### 30. What is the load factor in HashMap?
**Answer:** Ratio of number of entries to number of buckets. Default is 0.75. When
load factor is exceeded, HashMap is rehashed (capacity doubled).
---
## Exception Handling
### 31. What is exception handling in Java?
**Answer:** Mechanism to handle runtime errors gracefully without crashing the
program. Uses try-catch-finally blocks and throw/throws keywords.
### 32. What is the difference between checked and unchecked exceptions?
**Answer:**
- **Checked exceptions**: Compile-time exceptions that must be handled
(IOException, SQLException)
- **Unchecked exceptions**: Runtime exceptions that may or may not be handled
(NullPointerException, ArrayIndexOutOfBoundsException)
### 33. What is the exception hierarchy in Java?
**Answer:**
```
Throwable
├── Error (OutOfMemoryError, StackOverflowError)
└── Exception
├── Checked Exceptions (IOException, SQLException)
└── RuntimeException (Unchecked)
├── NullPointerException
├── ArrayIndexOutOfBoundsException
└── IllegalArgumentException
```
### 34. What is the difference between throw and throws?
**Answer:**
- **throw**: Used to explicitly throw an exception
- **throws**: Used in method signature to declare exceptions that method might
throw
```java
public void method() throws IOException {
if (condition) {
throw new IOException("Error occurred");
}
}
```
### 35. What is the difference between final, finally, and finalize?
**Answer:**
- **final**: Keyword for constants, preventing inheritance/overriding
- **finally**: Block that executes regardless of exception occurrence
- **finalize**: Method called by garbage collector before object destruction
### 36. Can we have multiple catch blocks for a try block?
**Answer:** Yes, multiple catch blocks are allowed. More specific exceptions should
be caught first, then general ones.
```java
try {
// code
} catch (FileNotFoundException e) {
// handle specific exception
} catch (IOException e) {
// handle general exception
}
```
### 37. What happens if an exception is thrown in finally block?
**Answer:** Exception from finally block will suppress the original exception. The
finally block exception will be thrown to the caller.
### 38. What is try-with-resources?
**Answer:** Java 7 feature for automatic resource management. Resources are
automatically closed.
```java
try (FileReader file = new FileReader("file.txt")) {
// use file
} catch (IOException e) {
// handle exception
} // file is automatically closed
```
### 39. Can we write code after finally block?
**Answer:** Yes, code can be written after finally block and will execute normally
unless an exception is thrown from finally block.
### 40. What is exception chaining?
**Answer:** Process of handling one exception and throwing another exception with
the original exception as cause.
```java
try {
// code that throws SQLException
} catch (SQLException e) {
throw new ServiceException("Service failed", e);
}
```
---
## Multithreading
### 41. What is multithreading?
**Answer:** Ability to execute multiple threads concurrently within a single
process. Each thread runs independently but shares the process resources.
### 42. What is the difference between process and thread?
**Answer:**
| Process | Thread |
|---------|--------|
| Independent execution unit | Lightweight subprocess |
| Separate memory space | Shared memory space |
| Heavy context switching | Light context switching |
| Inter-process communication required | Direct communication possible |
### 43. How can you create a thread in Java?
**Answer:** Three ways:
1. **Extending Thread class**:
```java
class MyThread extends Thread {
public void run() { System.out.println("Thread running"); }
}
MyThread t = new MyThread();
t.start();
```
2. **Implementing Runnable interface**:
```java
class MyRunnable implements Runnable {
public void run() { System.out.println("Thread running"); }
}
Thread t = new Thread(new MyRunnable());
t.start();
```
3. **Using Callable interface** (returns value):
```java
Callable<String> callable = () -> "Result";
Future<String> future = executor.submit(callable);
```
### 44. What is the difference between start() and run() methods?
**Answer:**
- **start()**: Creates new thread and calls run() method in that thread
- **run()**: Executes in current thread, doesn't create new thread
### 45. What are thread states in Java?
**Answer:** Thread states:
- **NEW**: Thread created but not started
- **RUNNABLE**: Thread executing or ready to execute
- **BLOCKED**: Thread blocked waiting for monitor lock
- **WAITING**: Thread waiting indefinitely for another thread
- **TIMED_WAITING**: Thread waiting for specified time
- **TERMINATED**: Thread completed execution
### 46. What is synchronization?
**Answer:** Mechanism to control access of shared resources by multiple threads.
Prevents data inconsistency and thread interference.
```java
synchronized void method() {
// synchronized method
}
synchronized(obj) {
// synchronized block
}
```
### 47. What is the difference between synchronized method and synchronized block?
**Answer:**
| Synchronized Method | Synchronized Block |
|--------------------|--------------------|
| Entire method is synchronized | Only specific code block |
| Uses object's monitor | Can use any object's monitor |
| Less flexible | More flexible and efficient |
### 48. What is deadlock?
**Answer:** Situation where two or more threads are blocked forever, each waiting
for the other to release a resource.
```java
// Thread 1: locks A, waits for B
// Thread 2: locks B, waits for A
// Result: Deadlock
```
### 49. How can you avoid deadlock?
**Answer:** Deadlock prevention strategies:
- **Avoid nested locks**
- **Lock ordering**: Always acquire locks in same order
- **Timeout**: Use tryLock() with timeout
- **Deadlock detection**: Monitor and break deadlocks
### 50. What is thread pool?
**Answer:** Collection of pre-initialized threads that can be reused for executing
tasks. Benefits:
- Reduces thread creation overhead
- Controls maximum number of threads
- Better resource management
```java
ExecutorService executor = Executors.newFixedThreadPool(5);
executor.submit(() -> System.out.println("Task executed"));
```
---
## String Handling
### 51. Why is String immutable in Java?
**Answer:** Strings are immutable for:
- **Security**: String values can't be changed after creation
- **Thread safety**: Immutable objects are inherently thread-safe
- **String pool optimization**: Same strings can share memory
- **Hashcode caching**: Hash value can be cached
### 52. What is String pool?
**Answer:** Memory area in heap where string literals are stored. JVM maintains
pool to optimize memory by reusing string objects.
```java
String s1 = "hello"; // Goes to string pool
String s2 = "hello"; // References same object in pool
String s3 = new String("hello"); // Creates new object in heap
```
### 53. What are different ways to create String objects?
**Answer:**
1. **String literal**: `String s = "hello";`
2. **Using new keyword**: `String s = new String("hello");`
3. **Using StringBuilder/StringBuffer**: `String s = new
StringBuilder("hello").toString();`
4. **Using char array**: `String s = new String(charArray);`
### 54. What is intern() method?
**Answer:** Returns canonical representation of string. If string exists in pool,
returns reference to pool object; otherwise, adds string to pool and returns
reference.
```java
String s1 = new String("hello").intern();
String s2 = "hello";
System.out.println(s1 == s2); // true
```
### 55. Performance comparison: String vs StringBuffer vs StringBuilder?
**Answer:**
- **String**: Slowest due to immutability (creates new objects)
- **StringBuffer**: Moderate (synchronized methods add overhead)
- **StringBuilder**: Fastest for single-threaded operations
### 56. Common String methods?
**Answer:**
```java
String s = "Hello World";
s.length() // 11
s.charAt(0) // 'H'
s.substring(0, 5) // "Hello"
s.indexOf("o") // 4
s.replace("o", "a") // "Hella Warld"
s.split(" ") // ["Hello", "World"]
s.toUpperCase() // "HELLO WORLD"
s.trim() // removes leading/trailing spaces
```
### 57. What is the difference between String.valueOf() and toString()?
**Answer:**
- **String.valueOf()**: Static method, handles null values safely
- **toString()**: Instance method, throws NullPointerException for null
```java
String s = null;
String.valueOf(s); // "null"
s.toString(); // NullPointerException
```
### 58. How to compare strings ignoring case?
**Answer:** Use `equalsIgnoreCase()` method:
```java
String s1 = "Hello";
String s2 = "HELLO";
s1.equalsIgnoreCase(s2); // true
```
### 59. How to check if string is empty or null?
**Answer:**
```java
// Check for null and empty
if (str == null || str.isEmpty()) { }
// Check for null, empty, and whitespace
if (str == null || str.trim().isEmpty()) { }
// Java 11+ - isBlank() method
if (str == null || str.isBlank()) { }
```
### 60. What is StringTokenizer?
**Answer:** Legacy class for breaking strings into tokens. Replaced by `split()`
method in modern Java.
```java
StringTokenizer st = new StringTokenizer("Java,Python,C++", ",");
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
```
---
## Java 8+ Features
### 61. What are Lambda expressions?
**Answer:** Anonymous functions that provide concise way to represent functional
interfaces. Enable functional programming in Java.
```java
// Traditional approach
Comparator<String> comp = new Comparator<String>() {
public int compare(String a, String b) { return a.compareTo(b); }
};
// Lambda expression
Comparator<String> comp = (a, b) -> a.compareTo(b);
```
### 62. What are functional interfaces?
**Answer:** Interfaces with exactly one abstract method. Can be used as lambda
expression targets.
```java
@FunctionalInterface
interface Calculator {
int calculate(int a, int b);
}
Calculator add = (a, b) -> a + b;
```
### 63. What are method references?
**Answer:** Shorthand notation for lambda expressions that call existing methods.
```java
// Lambda expression
list.forEach(s -> System.out.println(s));
// Method reference
list.forEach(System.out::println);
// Types:
// Static method: ClassName::methodName
// Instance method: instance::methodName
// Constructor: ClassName::new
```
### 64. What is Stream API?
**Answer:** Feature for processing collections in functional style. Provides
operations like map, filter, reduce, collect.
```java
List<String> names = Arrays.asList("John", "Jane", "Jack");
names.stream()
.filter(name -> name.startsWith("J"))
.map(String::toUpperCase)
.forEach(System.out::println);
```
### 65. What are intermediate and terminal operations in Stream?
**Answer:**
- **Intermediate**: Return stream, lazy evaluation (filter, map, sorted)
- **Terminal**: Return non-stream result, trigger processing (forEach, collect,
reduce)
### 66. What is Optional class?
**Answer:** Container that may or may not contain a value. Helps avoid
NullPointerException.
```java
Optional<String> optional = Optional.of("value");
optional.ifPresent(System.out::println);
String value = optional.orElse("default");
```
### 67. What are default methods in interfaces?
**Answer:** Java 8 allows interfaces to have method implementations using `default`
keyword.
```java
interface Vehicle {
void start();
default void stop() { System.out.println("Vehicle stopped"); }
}
```
### 68. What is the forEach method?
**Answer:** Method introduced in Iterable interface for iterating collections using
lambda expressions.
```java
List<String> list = Arrays.asList("a", "b", "c");
list.forEach(System.out::println);
```
### 69. What are common functional interfaces in Java 8?
**Answer:**
- **Predicate<T>**: boolean test(T t) - for filtering
- **Function<T,R>**: R apply(T t) - for mapping
- **Consumer<T>**: void accept(T t) - for consuming
- **Supplier<T>**: T get() - for supplying
- **UnaryOperator<T>**: T apply(T t) - special case of Function
### 70. What is parallel stream?
**Answer:** Stream that processes elements in parallel using multiple threads.
```java
list.parallelStream()
.filter(x -> x > 10)
.map(x -> x * 2)
.collect(Collectors.toList());
```
---
## Memory Management
### 71. Explain Java memory model.
**Answer:** Java memory is divided into:
- **Heap Memory**: Object storage, divided into Young Generation (Eden, S0, S1) and
Old Generation
- **Non-Heap Memory**: Method Area (class metadata), Code Cache, Compressed Class
Space
- **Stack Memory**: Thread-specific, stores local variables and method calls
- **PC Registers**: Program counter for each thread
- **Native Method Stacks**: For native method calls
### 72. What is garbage collection?
**Answer:** Automatic memory management process that identifies and frees unused
objects to prevent memory leaks.
### 73. What are different types of garbage collectors?
**Answer:**
- **Serial GC**: Single-threaded, suitable for small applications
- **Parallel GC**: Multi-threaded, default for server applications
- **CMS (Concurrent Mark Sweep)**: Low-latency collector
- **G1GC**: Low-pause collector for large heaps
- **ZGC/Shenandoah**: Ultra-low latency collectors (Java 11+)
### 74. What is the difference between stack and heap memory?
**Answer:**
| Stack Memory | Heap Memory |
|--------------|-------------|
| Thread-specific | Shared among threads |
| Stores local variables | Stores objects |
| LIFO structure | No specific order |
| Fast access | Slower access |
| Limited size | Larger size |
| Automatic cleanup | Requires garbage collection |
### 75. What causes OutOfMemoryError?
**Answer:** Occurs when:
- **Heap space exhausted**: Too many objects created
- **Metaspace full**: Too many classes loaded
- **Stack overflow**: Deep recursion or large local variables
- **Memory leaks**: Objects not properly dereferenced
### 76. What are strong, weak, soft, and phantom references?
**Answer:**
- **Strong Reference**: Normal references, prevents GC
- **Weak Reference**: Doesn't prevent GC, collected in next GC cycle
- **Soft Reference**: Collected when memory is low
- **Phantom Reference**: Used for cleanup actions, object already collected
### 77. What is memory leak in Java?
**Answer:** Situation where objects are no longer used but still referenced,
preventing garbage collection. Common causes:
- Unclosed resources
- Static collections holding references
- Inner class references to outer class
- Event listeners not removed
### 78. How can you force garbage collection?
**Answer:** Use `System.gc()` or `Runtime.gc()`, but it's only a suggestion to JVM.
JVM may choose to ignore it.
### 79. What is finalize() method?
**Answer:** Method called by garbage collector before object destruction.
Deprecated in Java 9+ due to performance issues.
```java
@Override
protected void finalize() throws Throwable {
// cleanup code
super.finalize();
}
```
### 80. What are JVM tuning parameters?
**Answer:** Common parameters:
- `-Xms`: Initial heap size
- `-Xmx`: Maximum heap size
- `-XX:NewRatio`: Ratio of old to young generation
- `-XX:+UseG1GC`: Use G1 garbage collector
- `-XX:+PrintGCDetails`: Print GC information
---
## Design Patterns
### 81. What are design patterns?
**Answer:** Reusable solutions to commonly occurring problems in software design.
Provide best practices and proven development paradigms.
### 82. What is Singleton pattern?
**Answer:** Ensures only one instance of a class exists and provides global access
point.
```java
public class Singleton {
private static volatile Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
```
### 83. What is Factory pattern?
**Answer:** Creates objects without specifying their concrete classes. Delegates
object creation to factory methods.
```java
interface Shape {
void draw();
}
class Circle implements Shape {
public void draw() { System.out.println("Drawing Circle"); }
}
class ShapeFactory {
public static Shape getShape(String type) {
if ("circle".equals(type)) return new Circle();
return null;
}
}
```
### 84. What is Observer pattern?
**Answer:** Defines one-to-many dependency between objects. When one object changes
state, all dependents are notified.
```java
interface Observer {
void update(String message);
}
class Subject {
private List<Observer> observers = new ArrayList<>();
public void addObserver(Observer o) { observers.add(o); }
public void notifyObservers(String msg) {
observers.forEach(o -> o.update(msg));
}
}
```
### 85. What is Builder pattern?
**Answer:** Constructs complex objects step by step. Separates construction from
representation.
```java
class Product {
private String name;
private double price;
public static class Builder {
private String name;
private double price;
public Builder setName(String name) { this.name = name; return this; }
public Builder setPrice(double price) { this.price = price; return this; }
public Product build() {
Product p = new Product();
p.name = this.name;
p.price = this.price;
return p;
}
}
}
// Usage: new Product.Builder().setName("Laptop").setPrice(1000).build();
```
### 86. What is MVC pattern?
**Answer:** Separates application into three components:
- **Model**: Data and business logic
- **View**: User interface
- **Controller**: Handles user input and coordinates between Model and View
### 87. What is DAO pattern?
**Answer:** Data Access Object pattern provides abstract interface to database
operations, separating data access logic from business logic.
```java
interface UserDAO {
void save(User user);
User findById(int id);
List<User> findAll();
}
class UserDAOImpl implements UserDAO {
// Database operations implementation
}
```
### 88. What is Strategy pattern?
**Answer:** Defines family of algorithms, encapsulates each one, and makes them
interchangeable.
```java
interface PaymentStrategy {
void pay(double amount);
}
class CreditCardPayment implements PaymentStrategy {
public void pay(double amount) { /* credit card logic */ }
}
class PayPalPayment implements PaymentStrategy {
public void pay(double amount) { /* PayPal logic */ }
}
```
### 89. What is Adapter pattern?
**Answer:** Allows incompatible interfaces to work together by wrapping existing
class with new interface.
```java
class LegacyPrinter {
public void oldPrint(String text) { /* legacy implementation */ }
}
interface ModernPrinter {
void print(String text);
}
class PrinterAdapter implements ModernPrinter {
private LegacyPrinter legacyPrinter;
public void print(String text) {
legacyPrinter.oldPrint(text);
}
}
```
### 90. What is Decorator pattern?
**Answer:** Adds new functionality to objects dynamically without altering their
structure.
```java
interface Coffee {
double cost();
}
class SimpleCoffee implements Coffee {
public double cost() { return 2.0x