1. OOPs Concepts & Real-World Examples
Q1: What is Encapsulation and how is it implemented?
Answer: Encapsulation is the mechanism of wrapping data (variables) and code acting on the data (methods) together as a single unit. It protects an object's internal state from unintended modification.
- Implementation: Declare class variables as
privateand providepublicgetter and setter methods with validation logic.
Q2: What is the difference between Method Overloading and Method Overriding?
| Feature | Method Overloading (Compile-Time) | Method Overriding (Run-Time) |
|---|---|---|
| Location | Occurs within the same class | Occurs between Superclass and Subclass |
| Method Signature | Must have different parameters (count or type) | Must have the exact same parameters |
| Return Type | Can be different | Must be same or covariant |
private / static | Can overload private/static methods | Cannot override private or static methods |
2. Java Memory Model (Heap vs Stack)
Q3: How does JVM allocate memory between Stack and Heap?
- Stack Memory: Used for static memory allocation and the execution of threads. It contains primitive values specific to a method and references to objects in the Heap. Memory allocation follows LIFO (Last-In-First-Out) order and is very fast.
- Heap Memory: Used for dynamic memory allocation for Java Objects and JRE classes at runtime. Heap is shared across all running threads and is cleaned up by the Garbage Collector.
public class MemoryDemo {
public static void main(String[] args) {
int localVal = 100; // Stored in Stack frame
String greeting = new String("Hello"); // 'greeting' reference in Stack, String object in Heap
}
}3. Strings & Immutability
Q4: Why is `String` immutable in Java?
- String Constant Pool (SCP): Multiple references can point to the exact same String literal in the pool, saving immense RAM.
- Security: Strings are widely used to store sensitive information (Database URLs, Passwords, Network sockets). If mutable, an unauthorized thread could alter the connection string.
- Thread Safety: Because the state cannot change, Strings are automatically thread-safe without explicit synchronization.
- HashCode Caching: The hashcode is computed once and cached, making Strings ideal keys for
HashMap.
4. Collections Framework & HashMap Internals
Q5: How does `HashMap` work internally in Java?
HashMap works on the principle of Hashing. It stores key-value pairs in an array of Node<K,V> buckets.
- When you call
map.put(key, value), JVM computeskey.hashCode(). - The index is calculated as
index = hash & (n - 1)wherenis the bucket array length (default 16). - If two different keys map to the same bucket index (Hash Collision):
- In Java 7: Stored as a singly Linked List ($O(N)$ lookup).
- In Java 8+: If the bucket size exceeds 8 elements, the LinkedList transforms into a Balanced Red-Black Tree ($O(\log N)$ lookup).
5. Exception Handling & Best Practices
Q6: What is the difference between Checked and Unchecked Exceptions?
- Checked Exceptions (Compile-Time): Exceptions that extend
java.lang.Exception(excludingRuntimeException). The compiler forces you to handle them usingtry-catchor declare them withthrows(IOException,SQLException,ClassNotFoundException). - Unchecked Exceptions (Runtime): Exceptions that extend
java.lang.RuntimeException. They occur due to logical bugs or improper API usage and do not require mandatory compile-time handling (NullPointerException,ArrayIndexOutOfBoundsException,ArithmeticException).
Q7: What is Try-With-Resources and why is it preferred?
Introduced in Java 7, Try-With-Resources automatically closes any resource that implements java.lang.AutoCloseable (such as Database connections, File streams, and Sockets) once the try block completes, preventing resource leaks.
// Try-with-resources auto-closes BufferedReader
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ResourceDemo {
public static void readFile(String path) {
try (BufferedReader br = new BufferedReader(new FileReader(path))) {
System.out.println(br.readLine());
} catch (IOException e) {
System.err.println("Failed reading file: " + e.getMessage());
}
}
}6. Java 8 Streams & Lambda Expressions
Q8: What are Lambda Expressions and Functional Interfaces?
A Functional Interface is an interface with exactly one abstract method (e.g. Runnable, Callable, Predicate<T>, Function<T,R>, Consumer<T>). It is annotated with @FunctionalInterface.
Lambda expressions provide a clear and concise syntax to implement functional interfaces without writing anonymous inner classes.
Q9: How to filter, transform, and aggregate data using Java 8 Streams?
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class StreamsMasterclass {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
// 1. Filter even numbers and compute their squares
List<Integer> evenSquares = numbers.stream()
.filter(n -> n % 2 == 0)
.map(n -> n * n)
.collect(Collectors.toList());
System.out.println("Even Squares: " + evenSquares); // [4, 16, 36, 64, 100]
// 2. Reduce to compute sum
int totalSum = numbers.stream()
.reduce(0, Integer::sum);
System.out.println("Total Sum: " + totalSum); // 55
}
}