---
## JDBC & Database
### 91. What is JDBC?
**Answer:** Java Database Connectivity - API for connecting and executing queries
with databases. Provides standard interface for database operations.
### 92. What are the steps to connect to database using JDBC?
**Answer:**
1. **Load Driver**: `Class.forName("com.mysql.jdbc.Driver")`
2. **Create Connection**: `DriverManager.getConnection(url, username, password)`
3. **Create Statement**: `connection.createStatement()`
4. **Execute Query**: `statement.executeQuery("SELECT * FROM table")`
5. **Process Results**: Iterate through ResultSet
6. **Close Resources**: Close ResultSet, Statement, Connection
```java
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db",
"user", "pass");
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM users");
while(rs.next()) {
System.out.println(rs.getString("name"));
}
```
### 93. What is the difference between Statement, PreparedStatement, and
CallableStatement?
**Answer:**
| Statement | PreparedStatement | CallableStatement |
|-----------|------------------|-------------------|
| Static SQL queries | Parameterized queries | Stored procedures |
| Compiled every time | Pre-compiled | Pre-compiled |
| SQL injection prone | SQL injection safe | SQL injection safe |
| Slower performance | Better performance | Best for stored procedures |
### 94. What are the advantages of PreparedStatement?
**Answer:**
- **Performance**: Pre-compiled, faster execution
- **Security**: Prevents SQL injection attacks
- **Readability**: Cleaner code with parameters
- **Type Safety**: Automatic type conversion
```java
PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM users WHERE id = ?
AND name = ?");
pstmt.setInt(1, userId);
pstmt.setString(2, userName);
ResultSet rs = pstmt.executeQuery();
```
### 95. What is connection pooling?
**Answer:** Technique of creating and maintaining a cache of database connections
for reuse. Benefits:
- **Performance**: Eliminates connection creation overhead
- **Resource Management**: Controls maximum connections
- **Scalability**: Better handling of concurrent requests
### 96. What are JDBC drivers and their types?
**Answer:** Software components that enable Java applications to interact with
databases.
**Types:**
- **Type 1**: JDBC-ODBC Bridge (deprecated)
- **Type 2**: Native-API Driver (platform-specific)
- **Type 3**: Network Protocol Driver (middleware)
- **Type 4**: Thin Driver (pure Java, most common)
### 97. What is ResultSetMetaData?
**Answer:** Interface that provides information about ResultSet columns like column
count, names, types, etc.
```java
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
for(int i = 1; i <= columnCount; i++) {
System.out.println("Column: " + rsmd.getColumnName(i));
System.out.println("Type: " + rsmd.getColumnTypeName(i));
}
```
### 98. What is batch processing in JDBC?
**Answer:** Technique to execute multiple SQL statements as a single unit to
improve performance.
```java
Statement stmt = conn.createStatement();
stmt.addBatch("INSERT INTO users VALUES(1, 'John')");
stmt.addBatch("INSERT INTO users VALUES(2, 'Jane')");
stmt.addBatch("UPDATE users SET name='Johnny' WHERE id=1");
int[] results = stmt.executeBatch();
```
### 99. What are transaction properties (ACID)?
**Answer:**
- **Atomicity**: All operations succeed or fail together
- **Consistency**: Database remains in valid state
- **Isolation**: Concurrent transactions don't interfere
- **Durability**: Committed changes are permanent
### 100. How do you handle transactions in JDBC?
**Answer:**
```java
try {
conn.setAutoCommit(false); // Start transaction
// Execute multiple statements
stmt1.executeUpdate("INSERT INTO accounts VALUES(1, 1000)");
stmt2.executeUpdate("UPDATE accounts SET balance = balance - 100 WHERE id =
1");
conn.commit(); // Commit transaction
} catch (SQLException e) {
conn.rollback(); // Rollback on error
} finally {
conn.setAutoCommit(true); // Reset auto-commit
}
```
---
## Spring Framework Basics
### 101. What is Spring Framework?
**Answer:** Comprehensive framework for enterprise Java development. Provides:
- **Dependency Injection**: IoC container
- **Aspect-Oriented Programming**: Cross-cutting concerns
- **Data Access**: JDBC, ORM integration
- **Web Development**: Spring MVC
- **Security**: Spring Security
### 102. What is Dependency Injection?
**Answer:** Design pattern where objects receive their dependencies from external
source rather than creating them internally.
```java
// Without DI
class OrderService {
private PaymentService paymentService = new PaymentService();
}
// With DI
class OrderService {
private PaymentService paymentService;
public OrderService(PaymentService paymentService) {
this.paymentService = paymentService;
}
}
```
### 103. What is Inversion of Control (IoC)?
**Answer:** Principle where control of object creation and lifecycle is transferred
from application code to framework. Spring IoC container manages object creation,
wiring, and lifecycle.
### 104. What are the types of Dependency Injection?
**Answer:**
- **Constructor Injection**: Dependencies injected through constructor
- **Setter Injection**: Dependencies injected through setter methods
- **Field Injection**: Dependencies injected directly into fields (using
@Autowired)
### 105. What is ApplicationContext?
**Answer:** Central interface in Spring IoC container that provides:
- Bean factory functionality
- Resource loading
- Event publication
- Internationalization support
```java
ApplicationContext context = new
ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService = context.getBean(UserService.class);
```
### 106. What are Spring annotations?
**Answer:**
- **@Component**: Generic component
- **@Service**: Service layer component
- **@Repository**: Data access layer component
- **@Controller**: Web layer component
- **@Autowired**: Automatic dependency injection
- **@Qualifier**: Specify which bean to inject
- **@Value**: Inject property values
### 107. What is @Autowired annotation?
**Answer:** Annotation for automatic dependency injection. Spring automatically
injects matching beans.
```java
@Service
public class OrderService {
@Autowired
private PaymentService paymentService;
@Autowired
private UserRepository userRepository;
}
```
### 108. What is the difference between @Component, @Service, @Repository, and
@Controller?
**Answer:**
- **@Component**: Generic stereotype for any Spring component
- **@Service**: Business logic layer
- **@Repository**: Data access layer, enables exception translation
- **@Controller**: Web layer, handles HTTP requests
All are specialized versions of @Component with additional semantics.
### 109. What is Spring Boot?
**Answer:** Framework that simplifies Spring application development by providing:
- **Auto-configuration**: Automatic configuration based on classpath
- **Starter dependencies**: Pre-configured dependency sets
- **Embedded servers**: Tomcat, Jetty embedded
- **Production-ready features**: Metrics, health checks
### 110. What are Spring profiles?
**Answer:** Feature to segregate application configuration for different
environments.
```java
@Profile("development")
@Configuration
public class DevConfig {
// Development specific beans
}
@Profile("production")
@Configuration
public class ProdConfig {
// Production specific beans
}
```
### 111. What is Spring MVC?
**Answer:** Web framework based on Model-View-Controller pattern. Components:
- **DispatcherServlet**: Front controller
- **HandlerMapping**: Maps requests to handlers
- **Controller**: Handles requests and returns ModelAndView
- **ViewResolver**: Resolves view names to actual views
### 112. What is @RequestMapping?
**Answer:** Annotation for mapping HTTP requests to handler methods.
```java
@Controller
public class UserController {
@RequestMapping(value="/users", method=RequestMethod.GET)
public String getUsers(Model model) {
// logic
return "users";
}
@GetMapping("/users/{id}")
public String getUser(@PathVariable int id) {
// logic
return "user";
}
}
```
### 113. What are Spring Bean scopes?
**Answer:**
- **Singleton**: One instance per IoC container (default)
- **Prototype**: New instance every time requested
- **Request**: One instance per HTTP request
- **Session**: One instance per HTTP session
- **Application**: One instance per ServletContext
### 114. What is @Configuration annotation?
**Answer:** Indicates that class contains bean definitions. Used with @Bean methods
to register beans.
```java
@Configuration
public class AppConfig {
@Bean
public UserService userService() {
return new UserServiceImpl();
}
}
```
### 115. What is AOP in Spring?
**Answer:** Aspect-Oriented Programming enables separation of cross-cutting
concerns like logging, security, transactions.
```java
@Aspect
@Component
public class LoggingAspect {
@Before("execution(* com.example.service.*.*(..))")
public void logBefore(JoinPoint joinPoint) {
System.out.println("Executing: " + joinPoint.getSignature().getName());
}
}
```
---
## Coding Questions
### 116. Write a program to reverse a string.
**Answer:**
```java
public class StringReverse {
public static String reverse(String str) {
if (str == null || str.length() <= 1) {
return str;
}
StringBuilder sb = new StringBuilder();
for (int i = str.length() - 1; i >= 0; i--) {
sb.append(str.charAt(i));
}
return sb.toString();
}
// Using StringBuilder built-in method
public static String reverseBuiltIn(String str) {
return new StringBuilder(str).reverse().toString();
}
// Recursive approach
public static String reverseRecursive(String str) {
if (str == null || str.length() <= 1) {
return str;
}
return reverseRecursive(str.substring(1)) + str.charAt(0);
}
}
```
### 117. Write a program to check if a string is palindrome.
**Answer:**
```java
public class Palindrome {
public static boolean isPalindrome(String str) {
if (str == null) return false;
str = str.toLowerCase().replaceAll("[^a-zA-Z0-9]", "");
int left = 0, right = str.length() - 1;
while (left < right) {
if (str.charAt(left) != str.charAt(right)) {
return false;
}
left++;
right--;
}
return true;
}
// Using StringBuilder
public static boolean isPalindromeBuiltIn(String str) {
str = str.toLowerCase().replaceAll("[^a-zA-Z0-9]", "");
return str.equals(new StringBuilder(str).reverse().toString());
}
}
```
### 118. Write a program to find duplicate characters in a string.
**Answer:**
```java
import java.util.*;
public class DuplicateCharacters {
public static void findDuplicates(String str) {
Map<Character, Integer> charCount = new HashMap<>();
// Count occurrences
for (char c : str.toCharArray()) {
charCount.put(c, charCount.getOrDefault(c, 0) + 1);
}
// Print duplicates
System.out.println("Duplicate characters:");
for (Map.Entry<Character, Integer> entry : charCount.entrySet()) {
if (entry.getValue() > 1) {
System.out.println(entry.getKey() + " : " + entry.getValue());
}
}
}
// Using Set approach
public static void findDuplicatesSet(String str) {
Set<Character> unique = new HashSet<>();
Set<Character> duplicates = new HashSet<>();
for (char c : str.toCharArray()) {
if (!unique.add(c)) {
duplicates.add(c);
}
}
System.out.println("Duplicates: " + duplicates);
}
}
```
### 119. Write a program to find factorial of a number.
**Answer:**
```java
public class Factorial {
// Iterative approach
public static long factorial(int n) {
if (n < 0) throw new IllegalArgumentException("Number must be non-
negative");
long result = 1;
for (int i = 2; i <= n; i++) {
result *= i;
}
return result;
}
// Recursive approach
public static long factorialRecursive(int n) {
if (n < 0) throw new IllegalArgumentException("Number must be non-
negative");
if (n <= 1) return 1;
return n * factorialRecursive(n - 1);
}
// Using BigInteger for large numbers
public static BigInteger factorialBig(int n) {
BigInteger result = BigInteger.ONE;
for (int i = 2; i <= n; i++) {
result = result.multiply(BigInteger.valueOf(i));
}
return result;
}
}
```
### 120. Write a program to check if a number is prime.
**Answer:**
```java
public class PrimeNumber {
public static boolean isPrime(int n) {
if (n <= 1) return false;
if (n <= 3) return true;
if (n % 2 == 0 || n % 3 == 0) return false;
// Check for divisors from 5 to sqrt(n)
for (int i = 5; i * i <= n; i += 6) {
if (n % i == 0 || n % (i + 2) == 0) {
return false;
}
}
return true;
}
// Simple approach
public static boolean isPrimeSimple(int n) {
if (n <= 1) return false;
if (n == 2) return true;
if (n % 2 == 0) return false;
for (int i = 3; i * i <= n; i += 2) {
if (n % i == 0) return false;
}
return true;
}
}
```
### 121. Write a program to find Fibonacci series.
**Answer:**
```java
public class Fibonacci {
// Iterative approach
public static void fibonacciSeries(int n) {
int first = 0, second = 1;
if (n >= 1) System.out.print(first + " ");
if (n >= 2) System.out.print(second + " ");
for (int i = 3; i <= n; i++) {
int third = first + second;
System.out.print(third + " ");
first = second;
second = third;
}
}
// Recursive approach (less efficient)
public static int fibonacciRecursive(int n) {
if (n <= 1) return n;
return fibonacciRecursive(n - 1) + fibonacciRecursive(n - 2);
}
// Using arrays
public static int[] fibonacciArray(int n) {
if (n <= 0) return new int[0];
if (n == 1) return new int[]{0};
int[] fib = new int[n];
fib[0] = 0;
fib[1] = 1;
for (int i = 2; i < n; i++) {
fib[i] = fib[i-1] + fib[i-2];
}
return fib;
}
}
```
### 122. Write a program to sort an array using bubble sort.
**Answer:**
```java
public class BubbleSort {
public static void bubbleSort(int[] arr) {
int n = arr.length;
boolean swapped;
for (int i = 0; i < n - 1; i++) {
swapped = false;
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
// Swap elements
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
swapped = true;
}
}
// If no swapping occurred, array is sorted
if (!swapped) break;
}
}
// Generic version
public static <T extends Comparable<T>> void bubbleSort(T[] arr) {
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j].compareTo(arr[j + 1]) > 0) {
T temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
}
```
### 123. Write a program to find the largest and smallest elements in an array.
**Answer:**
```java
public class ArrayMinMax {
public static void findMinMax(int[] arr) {
if (arr == null || arr.length == 0) {
System.out.println("Array is empty");
return;
}
int min = arr[0];
int max = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] < min) {
min = arr[i];
}
if (arr[i] > max) {
max = arr[i];
}
}
System.out.println("Minimum: " + min);
System.out.println("Maximum: " + max);
}
// Using streams (Java 8+)
public static void findMinMaxStream(int[] arr) {
if (arr == null || arr.length == 0) return;
int min = Arrays.stream(arr).min().getAsInt();
int max = Arrays.stream(arr).max().getAsInt();
System.out.println("Minimum: " + min);
System.out.println("Maximum: " + max);
}
// Return as array
public static int[] getMinMax(int[] arr) {
if (arr == null || arr.length == 0) return new int[]{};
int min = arr[0], max = arr[0];
for (int num : arr) {
min = Math.min(min, num);
max = Math.max(max, num);
}
return new int[]{min, max};
}
}
```
### 124. Write a program to remove duplicates from an array.
**Answer:**
```java
import java.util.*;
public class RemoveDuplicates {
// Using HashSet
public static int[] removeDuplicates(int[] arr) {
Set<Integer> set = new LinkedHashSet<>();
for (int num : arr) {
set.add(num);
}
return set.stream().mapToInt(Integer::intValue).toArray();
}
// For sorted array (in-place)
public static int removeDuplicatesSorted(int[] arr) {
if (arr.length <= 1) return arr.length;
int uniqueIndex = 1;
for (int i = 1; i < arr.length; i++) {
if (arr[i] != arr[i-1]) {
arr[uniqueIndex] = arr[i];
uniqueIndex++;
}
}
return uniqueIndex;
}
// Using Java 8 streams
public static int[] removeDuplicatesStream(int[] arr) {
return Arrays.stream(arr).distinct().toArray();
}
// Preserve order without Set
public static List<Integer> removeDuplicatesList(int[] arr) {
List<Integer> result = new ArrayList<>();
for (int num : arr) {
if (!result.contains(num)) {
result.add(num);
}
}
return result;
}
}
```
### 125. Write a program to find the second largest element in an array.
**Answer:**
```java
public class SecondLargest {
public static int findSecondLargest(int[] arr) {
if (arr == null || arr.length < 2) {
throw new IllegalArgumentException("Array must have at least 2
elements");
}
int largest = Integer.MIN_VALUE;
int secondLargest = Integer.MIN_VALUE;
for (int num : arr) {
if (num > largest) {
secondLargest = largest;
largest = num;
} else if (num > secondLargest && num < largest) {
secondLargest = num;
}
}
if (secondLargest == Integer.MIN_VALUE) {
throw new IllegalArgumentException("No second largest element found");
}
return secondLargest;
}
// Using sorting approach
public static int findSecondLargestSort(int[] arr) {
if (arr.length < 2) return -1;
Integer[] boxed = Arrays.stream(arr).boxed().toArray(Integer[]::new);
Arrays.sort(boxed, Collections.reverseOrder());
// Find second distinct element
for (int i = 1; i < boxed.length; i++) {
if (!boxed[i].equals(boxed[0])) {
return boxed[i];
}
}
return -1; // No second largest found
}
// Using streams
public static int findSecondLargestStream(int[] arr) {
return Arrays.stream(arr)
.boxed()
.sorted(Collections.reverseOrder())
.distinct()
.skip(1)
.findFirst()
.orElse(-1);
}
}
```
### 126. Write a program to count vowels and consonants in a string.
**Answer:**
```java
public class VowelConsonantCounter {
public static void countVowelsConsonants(String str) {
if (str == null) {
System.out.println("String is null");
return;
}
str = str.toLowerCase();
int vowels = 0, consonants = 0;
String vowelChars = "aeiou";
for (char c : str.toCharArray()) {
if (Character.isLetter(c)) {
if (vowelChars.indexOf(c) != -1) {
vowels++;
} else {
consonants++;
}
}
}
System.out.println("Vowels: " + vowels);
System.out.println("Consonants: " + consonants);
}
// Using Java 8 streams
public static void countVowelsConsonantsStream(String str) {
if (str == null) return;
str = str.toLowerCase();
long vowels = str.chars()
.filter(Character::isLetter)
.filter(c -> "aeiou".indexOf(c) != -1)
.count();
long consonants = str.chars()
.filter(Character::isLetter)
.filter(c -> "aeiou".indexOf(c) == -1)
.count();
System.out.println("Vowels: " + vowels);
System.out.println("Consonants: " + consonants);
}
// Return as array
public static int[] getVowelConsonantCount(String str) {
if (str == null) return new int[]{0, 0};
str = str.toLowerCase();
int vowels = 0, consonants = 0;
for (char c : str.toCharArray()) {
if (Character.isLetter(c)) {
if ("aeiou".contains(String.valueOf(c))) {
vowels++;
} else {
consonants++;
}
}
}
return new int[]{vowels, consonants};
}
}
```
### 127. Write a program to find the missing number in an array of 1 to n.
**Answer:**
```java
public class MissingNumber {
// Using sum formula: n(n+1)/2
public static int findMissingNumber(int[] arr, int n) {
int expectedSum = n * (n + 1) / 2;
int actualSum = 0;
for (int num : arr) {
actualSum += num;
}
return expectedSum - actualSum;
}
// Using XOR approach
public static int findMissingNumberXOR(int[] arr, int n) {
int xor1 = 0; // XOR of all numbers from 1 to n
int xor2 = 0; // XOR of all numbers in array
// XOR all numbers from 1 to n
for (int i = 1; i <= n; i++) {
xor1 ^= i;
}
// XOR all numbers in array
for (int num : arr) {
xor2 ^= num;
}
return xor1 ^ xor2;
}
// Using boolean array approach
public static int findMissingNumberBoolean(int[] arr, int n) {
boolean[] present = new boolean[n + 1];
// Mark present numbers
for (int num : arr) {
if (num <= n) {
present[num] = true;
}
}
// Find missing number
for (int i = 1; i <= n; i++) {
if (!present[i]) {
return i;
}
}
return -1; // Should not reach here for valid input
}
// For multiple missing numbers
public static List<Integer> findMissingNumbers(int[] arr, int n) {
Set<Integer> present = new HashSet<>();
for (int num : arr) {
present.add(num);
}
List<Integer> missing = new ArrayList<>();
for (int i = 1; i <= n; i++) {
if (!present.contains(i)) {
missing.add(i);
}
}
return missing;
}
}
```
### 128. Write a program to check if two strings are anagrams.
**Answer:**
```java
import java.util.*;
public class AnagramChecker {
// Using sorting
public static boolean areAnagrams(String str1, String str2) {
if (str1 == null || str2 == null) return false;
if (str1.length() != str2.length()) return false;
// Remove spaces and convert to lowercase
str1 = str1.replaceAll("\\s+", "").toLowerCase();
str2 = str2.replaceAll("\\s+", "").toLowerCase();
char[] chars1 = str1.toCharArray();
char[] chars2 = str2.toCharArray();
Arrays.sort(chars1);
Arrays.sort(chars2);
return Arrays.equals(chars1, chars2);
}
// Using character frequency count
public static boolean areAnagramsFrequency(String str1, String str2) {
if (str1 == null || str2 == null) return false;
if (str1.length() != str2.length()) return false;
str1 = str1.replaceAll("\\s+", "").toLowerCase();
str2 = str2.replaceAll("\\s+", "").toLowerCase();
Map<Character, Integer> charCount = new HashMap<>();
// Count characters in first string
for (char c : str1.toCharArray()) {
charCount.put(c, charCount.getOrDefault(c, 0) + 1);
}
// Subtract characters from second string
for (char c : str2.toCharArray()) {
charCount.put(c, charCount.getOrDefault(c, 0) - 1);
if (charCount.get(c) == 0) {
charCount.remove(c);
}
}
return charCount.isEmpty();
}
// Using array for ASCII characters (more efficient)
public static boolean areAnagramsArray(String str1, String str2) {
if (str1.length() != str2.length()) return false;
int[] charCount = new int[256]; // ASCII characters
for (int i = 0; i < str1.length(); i++) {
charCount[str1.charAt(i)]++;
charCount[str2.charAt(i)]--;
}
for (int count : charCount) {
if (count != 0) return false;
}
return true;
}
}
```
### 129. Write a program to implement binary search.
**Answer:**
```java
public class BinarySearch {
// Iterative approach
public static int binarySearch(int[] arr, int target) {
int left = 0, right = arr.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2; // Avoid overflow
if (arr[mid] == target) {
return mid;
} else if (arr[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1; // Element not found
}
// Recursive approach
public static int binarySearchRecursive(int[] arr, int target, int left, int
right) {
if (left > right) {
return -1; // Element not found
}
int mid = left + (right - left) / 2;
if (arr[mid] == target) {
return mid;
} else if (arr[mid] < target) {# 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.0