Part 1: Core Java Deep Dive
Section 1: Java Basics
Q1: What are the main features of Java? Answer: Java is platform-independent, object-oriented, secure, robust, multi-threaded, and supports automatic memory management. It runs on the JVM, making it “write once, run anywhere.” Tip: Always mention strong typing and backward compatibility when discussing features in interviews.
Q2: Difference between JDK, JRE, and JVM? Answer:
- JDK: Java Development Kit – tools for development (javac, jar).
- JRE: Java Runtime Environment – JVM + standard libraries, for running Java apps.
- JVM: Java Virtual Machine – runs bytecode, handles memory, class loading, and garbage collection.
Q3: How does Java achieve platform independence? Answer: Java compiles source code into bytecode, which the JVM interprets or JIT-compiles on any platform.
Q4: Explain the difference between primitive and reference types. Answer: Primitives store actual values, have fixed memory, and are faster. References point to objects in the heap. Example:
int x = 10; // primitive
String s = "Java"; // reference
Q5: What are wrapper classes and autoboxing?
Answer:
Wrapper classes (Integer, Double) allow primitives to be used as objects. Autoboxing automatically converts primitives to wrapper objects and vice versa.
Integer x = 10; // autoboxing
int y = x; // unboxing
Section 2: Object-Oriented Programming (OOP)
Q6: Explain the four pillars of OOP in Java. Answer:
- Encapsulation: Hide data using private fields and getters/setters.
- Inheritance: Reuse and extend classes.
- Polymorphism: Ability to take multiple forms (method overloading & overriding).
- Abstraction: Hide implementation details using abstract classes or interfaces.
Q7: Difference between abstract class and interface?
Answer:
- Abstract class: Can have fields, concrete & abstract methods, single inheritance.
- Interface: Only method signatures (Java 8+ supports default/static methods), multiple inheritance allowed. Tip: Mention interfaces for designing flexible APIs.
Q8: Explain method overloading vs overriding. Answer:
- Overloading: Same method name, different parameters. Compile-time polymorphism.
- Overriding: Subclass provides specific implementation for parent method. Runtime polymorphism.
Q9: What is final keyword in Java?
Answer:
Used to declare constants, prevent method overriding, or class inheritance.
Q10: Difference between == and .equals()?
Answer:
== compares references; .equals() compares object content (if overridden).
Section 3: Collections Framework
Q11: Difference between List, Set, Map? Answer:
- List: Ordered, allows duplicates (
ArrayList,LinkedList). - Set: No duplicates, unordered (
HashSet,LinkedHashSet,TreeSet). - Map: Key-value pairs, keys unique (
HashMap,TreeMap).
Q12: Difference between ArrayList and LinkedList? Answer:
- ArrayList: Fast random access, slower insert/delete.
- LinkedList: Fast insert/delete, slower random access.
Q13: Explain HashMap internal working. Answer:
- Uses array of buckets + linked lists or tree nodes (Java 8+).
- Key’s hashCode determines bucket. Collisions handled via linked list or red-black tree.
Q14: Difference between HashMap and ConcurrentHashMap? Answer:
- HashMap: Not thread-safe.
- ConcurrentHashMap: Thread-safe, uses lock striping.
Q15: Difference between Comparable and Comparator? Answer:
- Comparable: Implemented by class, natural order (
compareTo). - Comparator: External class, custom ordering (
compare).
Q16: Explain fail-fast and fail-safe iterators. Answer:
- Fail-fast: Detects concurrent modification, throws
ConcurrentModificationException(ArrayList iterator). - Fail-safe: Works on copy, doesn’t throw exception (ConcurrentHashMap iterator).
Q17: When to use LinkedHashMap? Answer: When insertion order or access order must be preserved, e.g., LRU cache.
Q18: Difference between TreeMap and HashMap? Answer:
- TreeMap: Sorted by keys, log(n) access, implements
NavigableMap. - HashMap: Unordered, O(1) access.
Section 4: Streams & Functional Programming
Q19: What is a Stream in Java 8? Answer: A sequence of elements supporting aggregate operations (filter, map, reduce) in a functional style. Streams are lazy and can be parallelized.
Q20: Difference between intermediate and terminal operations? Answer:
- Intermediate: Returns another stream (
filter,map) – lazy evaluation. - Terminal: Produces result (
collect,forEach) – triggers processing.
Q21: Example of parallel stream.
List<Integer> nums = Arrays.asList(1,2,3,4,5);
int sum = nums.parallelStream().mapToInt(Integer::intValue).sum();
Q22: Functional interfaces in Java 8?
Answer:
Predicate, Function, Consumer, Supplier, UnaryOperator, BinaryOperator.
Tip: Prepare examples of lambda usage in interviews.
Q23: Method references example.
List<String> names = Arrays.asList("Alice","Bob");
names.forEach(System.out::println);
Section 5: Concurrency & Multithreading
Q24: Difference between process and thread? Answer:
- Process: Independent, own memory, heavyweight.
- Thread: Lightweight, shares process memory, faster communication.
Q25: How do you create a thread in Java?
// Extend Thread
class MyThread extends Thread {
public void run() { System.out.println("Running"); }
}
// Implement Runnable
class MyTask implements Runnable {
public void run() { System.out.println("Task"); }
}
Q26: What is thread safety? Answer: Multiple threads accessing shared resources without causing inconsistent state. Achieved via synchronized blocks, locks, atomic classes.
Q27: Explain volatile keyword.
Answer:
Ensures visibility of changes to variables across threads; doesn’t guarantee atomicity.
Q28: Difference between synchronized and ReentrantLock?
Answer:
synchronized: Simpler, intrinsic lock, no tryLock.ReentrantLock: More flexible, supports tryLock, fairness, multiple conditions.
Q29: Explain ExecutorService usage.
ExecutorService executor = Executors.newFixedThreadPool(5);
executor.submit(() -> System.out.println("Task executed"));
executor.shutdown();
Q30: Difference between Callable and Runnable?
Answer:
- Runnable: Returns nothing, cannot throw checked exceptions.
- Callable: Returns value, can throw exception, used with
Future.
Section 6: JVM Internals & Memory Management
Q31: Explain JVM memory model. Answer:
- Heap: Objects, GC-managed.
- Stack: Method calls, local primitives.
- Method area: Class metadata, constants.
- PC Register & Native method stack: Thread execution and native code.
Q32: What is garbage collection (GC)? Answer: Automatic memory cleanup for unreachable objects. Main collectors: Serial, Parallel, CMS, G1.
Q33: Difference between minor and major GC? Answer:
- Minor GC: Cleans young generation. Fast.
- Major/Full GC: Cleans old generation. Expensive.
Q34: Explain strong, weak, soft, phantom references. Answer: Used to control object reachability and GC behavior. Example: WeakHashMap uses weak keys.
Q35: What is JVM tuning? Answer: Adjusting heap size, GC strategy, thread stack size for performance-critical applications.
Section 7: Design Patterns
Q36: Explain Singleton pattern and its thread-safe implementation.
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;
}
}
Q37: Builder pattern use-case.
public class User {
private String name; private int age;
private User(Builder b) { name = b.name; age = b.age; }
public static class Builder {
private String name; private int age;
public Builder setName(String name){ this.name=name; return this; }
public Builder setAge(int age){ this.age=age; return this; }
public User build(){ return new User(this); }
}
}
Q38: Factory pattern example.
interface Shape { void draw(); }
class Circle implements Shape { public void draw() { System.out.println("Circle"); } }
class ShapeFactory {
public static Shape getShape(String type) {
if(type.equals("circle")) return new Circle();
return null;
}
}
Q39: Observer pattern scenario. Used in event-driven systems: listeners notify subscribers of changes (e.g., stock price updates).
Q40: Strategy pattern use-case. Used to define algorithms that can be swapped at runtime (e.g., payment gateway selection).
Section 8: Advanced Java Concepts
Q41: What is Reflection in Java and when is it used? Answer: Reflection allows inspection and manipulation of classes, methods, fields, and constructors at runtime. Useful in frameworks like Spring for dependency injection and testing. Example:
Class<?> clazz = Class.forName("com.example.MyClass");
Method m = clazz.getMethod("myMethod");
m.invoke(clazz.getDeclaredConstructor().newInstance());
Pitfall: Reflection bypasses compile-time checks and can impact performance.
Q42: Explain Generics in Java. Why are they important? Answer: Generics provide type safety at compile-time and reduce casting.
List<String> names = new ArrayList<>();
names.add("Alice"); // type-safe
Without generics, you’d need casts which are error-prone.
Q43: Difference between checked and unchecked exceptions?
Answer:
- Checked: Must be declared or caught (
IOException). - Unchecked: Runtime exceptions, can be ignored (
NullPointerException).
Q44: Explain Java Annotations and custom annotation example. Answer: Annotations provide metadata for classes, methods, or fields.
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface LogExecutionTime {}
Tip: Explain usage in Spring AOP and validation.
Q45: Serialization and deserialization in Java?
Answer:
Serialization converts objects to bytes for storage or network transfer. Must implement Serializable. Deserialization reconstructs the object.
Pitfall: Always manage serialVersionUID to avoid version mismatch.
Q46: Difference between == and equals() in Collections context?
Answer:
Hash-based collections use hashCode() and equals() to store and retrieve objects. Implement both properly to avoid incorrect behavior in HashMap or HashSet.
Q47: Explain Optional in Java 8+.
Answer:
Optional prevents NullPointerException by explicitly representing absence of value.
Optional<String> name = Optional.ofNullable(getName());
name.ifPresent(System.out::println);
Q48: Difference between String, StringBuilder, and StringBuffer? Answer:
- String: Immutable, slower for concatenation.
- StringBuilder: Mutable, not thread-safe, fast.
- StringBuffer: Mutable, thread-safe, slower than StringBuilder.
Q49: What are lambda expressions and why are they used? Answer: Provide a concise way to represent functional interfaces. Reduce boilerplate and enhance readability.
List<Integer> nums = Arrays.asList(1,2,3);
nums.forEach(n -> System.out.println(n));
Q50: Explain method references and constructor references.
// Method reference
List<String> names = Arrays.asList("Alice","Bob");
names.forEach(System.out::println);
// Constructor reference
Supplier<List<String>> listSupplier = ArrayList::new;
Section 9: I/O & NIO
Q51: Difference between FileReader/FileWriter and BufferedReader/BufferedWriter?
Answer:
Buffered classes wrap basic readers/writers to improve performance with internal buffers.
Q52: What is Java NIO? Answer: New I/O provides non-blocking, channel-based API. Useful for high-performance network/server applications.
Q53: Explain Channels and Buffers. Answer:
- Buffer: Container for data.
- Channel: Connection to I/O device, reads/writes buffers efficiently.
Q54: Example of reading a file using NIO.
Path path = Paths.get("file.txt");
List<String> lines = Files.readAllLines(path);
Section 10: Exception Handling
Q55: Difference between throw and throws? Answer:
throw: Used to throw an exception object.throws: Declares exceptions a method may throw.
Q56: How does try-with-resources work?
Answer:
Automatically closes resources implementing AutoCloseable.
try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
System.out.println(br.readLine());
}
Q57: Explain custom exception creation.
class MyException extends Exception {
public MyException(String message) { super(message); }
}
Tip: Useful to convey domain-specific errors in enterprise applications.
Section 11: Advanced Concurrency
Q58: Explain CountDownLatch and CyclicBarrier.
CountDownLatch: One-time countdown to start or end threads.CyclicBarrier: Reusable barrier for threads to wait until all reach a point.
Q59: Difference between Semaphore and ReentrantLock.
- Semaphore controls permits for resources.
- ReentrantLock is exclusive lock with more flexibility.
Q60: Explain ThreadLocal. Stores thread-specific variables, useful for per-thread DB connections or user context.
Q61: What are atomic classes?
Classes like AtomicInteger provide lock-free thread-safe operations. Example:
AtomicInteger counter = new AtomicInteger(0);
counter.incrementAndGet();
Q62: Executors vs Thread creation? Executors manage thread pool, avoid creating excessive threads manually, control lifecycle, and allow scheduling.
Section 12: Remaining Design Patterns
Q63: Prototype pattern example. Used to clone objects efficiently.
public class Prototype implements Cloneable {
public Prototype clone() throws CloneNotSupportedException {
return (Prototype) super.clone();
}
}
Q64: Adapter pattern use-case. Converts interface of one class to another expected by client. Example: Integrating legacy payment system with modern interface.
Q65: Facade pattern example.
Provides simplified interface over complex subsystem.
Example: Spring’s JdbcTemplate abstracts JDBC complexity.
Q66: Decorator pattern scenario. Enhances functionality dynamically (e.g., InputStream decorators like BufferedInputStream, DataInputStream).
Q67: Chain of Responsibility pattern. Used in request processing chains, e.g., Spring MVC HandlerInterceptor chain.
Q68: Command pattern example. Encapsulates request as object. Used in task scheduling and undo operations.
Q69: Observer vs EventListener in Java. Observer: classic pattern. EventListener: Java-specific interface for GUI or event-driven programming.
Q70: Strategy vs Template Method. Strategy: runtime behavior swapping. Template: fixed steps with customizable hooks.
Section 13: Java 8+ Features
Q71: Stream reduction and collect example.
List<Integer> nums = Arrays.asList(1,2,3,4);
int sum = nums.stream().reduce(0, Integer::sum);
List<String> names = Stream.of("Alice","Bob").collect(Collectors.toList());
Q72: Optional chaining example.
Optional<User> user = findUser();
String email = user.map(User::getEmail).orElse("notfound@example.com");
Q73: Default methods in interfaces.
interface Logger {
default void log(String msg) { System.out.println(msg); }
}
Q74: Java 9 Modules – purpose? Encapsulation of packages and better dependency control for large applications.
Q75: Var keyword in Java 10. Type inference for local variables.
Q76: Record classes in Java 16+. Compact immutable data carriers.
record User(String name, int age) {}
Q77: Sealed classes (Java 17). Restrict subclassing for better maintainability.
Q78: Pattern matching with instanceof.
if(obj instanceof String s) {
System.out.println(s.length());
}
Q79: Text blocks (Java 15). Multi-line string literals:
String html = """
<html>
<body>Hello</body>
</html>
""";
Q80: Records + Streams combined example.
List<User> users = List.of(new User("Alice",25), new User("Bob",30));
List<String> names = users.stream().map(User::name).collect(Collectors.toList());