■ Advanced Java Mega Handbook (Landscape Layout)
■ Block 1 – Advanced Language Features
■ Enums in Depth
Enums in Java are classes that define a fixed set of constants. They can have fields, methods, and constructors.
enum Day {
MONDAY("Start of week"),
FRIDAY("Almost weekend"),
SUNDAY("Weekend");
private String description;
Day(String description) { this.description = description; }
public String getDescription() { return description; }
}
public class EnumDemo {
public static void main(String[] args) {
for (Day d : Day.values()) {
System.out.println(d + " : " + d.getDescription());
}
}
}
■ Annotations
Annotations attach metadata to code. They can be processed at compile time or read via reflection at runtime.
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface Test {}
public class MyTests {
@Test
public void testMethod() { System.out.println("Running test..."); }
}
■ Reflection API
Reflection lets you inspect classes, methods, fields, and annotations at runtime and even access private members.
import java.lang.reflect.*;
class Person { private String name = "John"; }
public class ReflectionDemo {
public static void main(String[] args) throws Exception {
Person p = new Person();
Field f = p.getClass().getDeclaredField("name");
f.setAccessible(true);
System.out.println("Private field value: " + f.get(p));
}
}
■ Inner Classes
Inner classes can be static, non-static, local, or anonymous and help encapsulate helper types.
class Outer {
private String message = "Hello";
class Inner { void print() { System.out.println(message); } }
static class StaticInner { void ping() { System.out.println("StaticInner"); } }
}
public class Test {
public static void main(String[] args) {
new Outer().new Inner().print();
new Outer.StaticInner().ping();
}
}
■ Sealed Classes & Records
Sealed classes restrict inheritance to a closed set of subclasses. Records are concise immutable data carriers.
sealed class Shape permits Circle, Square {}
final class Circle extends Shape {}
final class Square extends Shape {}
record Point(int x, int y) {}
public class Demo {
public static void main(String[] args) {
System.out.println(new Point(3,4));
}
}
■ Mini Quiz – Block 1
Question Answer
Can enums have methods in Java? Yes, enums are classes and can have fields, methods, and constructors.
What does @Retention control? Whether an annotation is kept in SOURCE, CLASS, or RUNTIME.
What can reflection do? Inspect and access classes/members at runtime, even private ones (with setAccessible).
Static vs non-static inner class? Static inner class cannot access outer instance; non-static can.
■ Block 2 – Collections & Generics
■ Java Collections Framework
The Collections Framework provides a unified architecture for storing and manipulating groups of objects. It includes core interfaces (List, Set, Queue,
Map), implementations, and utility algorithms.
import java.util.*;
public class CollectionsDemo {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("A");
list.add("B");
list.add("A"); // allows duplicates
Set<String> set = new HashSet<>();
set.add("A");
set.add("B");
set.add("A"); // ignores duplicate
System.out.println("List: " + list);
System.out.println("Set: " + set);
}
}
■ Fail-Fast vs Fail-Safe Iterators
Fail-Fast iterators throw ConcurrentModificationException if a collection is structurally modified during iteration. Fail-Safe iterators operate on a copy,
avoiding exceptions but not reflecting updates.
import java.util.*;
public class FailFastDemo {
public static void main(String[] args) {
List<String> list = new ArrayList<>(Arrays.asList("A", "B", "C"));
for (String s : list) {
if (s.equals("B")) list.remove(s); // throws ConcurrentModificationException
}
}
}
import java.util.concurrent.CopyOnWriteArrayList;
public class FailSafeDemo {
public static void main(String[] args) {
CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>(new String[]{"A", "B", "C"});
for (String s : list) {
if (s.equals("B")) list.remove(s); // no exception
}
System.out.println(list);
}
}
■ Generics
Generics allow classes, interfaces, and methods to operate on specified types safely, eliminating casts and providing compile-time checks.
class Box<T> {
private T value;
public void set(T value) { this.value = value; }
public T get() { return value; }
}
public class GenericDemo {
public static void main(String[] args) {
Box<String> stringBox = new Box<>();
stringBox.set("Hello");
System.out.println(stringBox.get());
Box<Integer> intBox = new Box<>();
intBox.set(123);
System.out.println(intBox.get());
}
}
■ Generics Wildcards
Wildcard Usage Example
<?> Unbounded wildcard List<?> list
<? extends T> Upper bounded (subtypes of T) List<? extends Number> list
<? super T> Lower bounded (supertypes of T) List<? super Integer> list
■ Mini Quiz – Block 2
Question Answer
Difference between List and Set? List allows duplicates, maintains order. Set disallows duplicates, no guaranteed order.
What happens in a Fail-Fast iterator? Throws ConcurrentModificationException when collection is modified.
What is type erasure? Generic types are replaced with Object (or upper bound) at compile-time.
When to use <? super T>? When writing data into a collection (contravariant usage).
■ Block 3 – Multithreading & Concurrency
■ Thread Lifecycle
A Java thread can be in several states: NEW, RUNNABLE, RUNNING, WAITING, TIMED_WAITING, BLOCKED, and TERMINATED.
class MyThread extends Thread {
public void run() {
System.out.println("Thread running");
}
}
public class ThreadDemo {
public static void main(String[] args) {
Thread t = new MyThread();
t.start(); // moves from NEW -> RUNNABLE -> RUNNING
}
}
■ Executors Framework
Executors decouple task submission from thread management. ExecutorService provides thread pooling.
import java.util.concurrent.*;
public class ExecutorDemo {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(2);
for (int i = 0; i < 5; i++) {
executor.submit(() -> System.out.println("Task executed by " + Thread.currentThread().getName()));
}
executor.shutdown();
}
}
■ Synchronization & Locks
Synchronization ensures mutual exclusion. Locks provide more flexibility than synchronized blocks.
class Counter {
private int count = 0;
public synchronized void increment() { count++; }
public int getCount() { return count; }
}
import java.util.concurrent.locks.*;
class Counter {
private int count = 0;
private Lock lock = new ReentrantLock();
public void increment() {
lock.lock();
try {
count++;
} finally {
lock.unlock();
}
}
}
Aspect synchronized Lock
Reentrancy Yes Yes
Try without blocking No Yes (tryLock)
Fairness option No Yes
Interruptible No Yes
■ Deadlock
Deadlock occurs when two or more threads are waiting indefinitely for resources locked by each other.
class A {}
class B {}
class DeadlockDemo {
private A a = new A();
private B b = new B();
public void method1() {
synchronized(a) {
synchronized(b) {
System.out.println("method1");
}
}
}
public void method2() {
synchronized(b) {
synchronized(a) {
System.out.println("method2");
}
}
}
}
■ Mini Quiz – Block 3
Question Answer
What are thread states in Java? NEW, RUNNABLE, RUNNING, WAITING, TIMED_WAITING, BLOCKED, TERMINATED.
What is the advantage of Executor framework? Manages thread pooling and task scheduling efficiently.
Difference between synchronized and Lock? Lock provides advanced features like tryLock, fairness, interruptibility.
What is a deadlock? A situation where threads wait indefinitely for each other’s resources.
■ Block 4 – JVM Internals & Performance
■ JVM Architecture
■ Garbage Collectors
GC Characteristics Best For
Serial GC Single-threaded, simple Small apps
Parallel GC Multi-threaded throughput Multi-core, high throughput
CMS Concurrent mark-sweep, low pause Low-latency apps (deprecated)
GC Characteristics Best For
G1 GC Region-based, balanced Large heaps, predictable pause
ZGC Scalable, ultra-low latency Apps needing low pause
Shenandoah Concurrent compaction Low-latency apps
■ Mini Quiz – Block 4
Question Answer
What are JVM runtime data areas? Heap, Stack, Method Area, PC Register, Native Method Stack.
Difference between Serial and Parallel GC? Serial uses one thread; Parallel uses multiple threads for throughput.
What does JIT do? Compiles frequently used bytecode into native machine code at runtime.
What is G1 GC? Collector that divides heap into regions for balanced collection.
■ Block 5 – Java I/O & NIO
■ Traditional I/O vs NIO
Traditional I/O is stream-based and blocking, while NIO is buffer-based and non-blocking. NIO provides better performance for scalable applications.
import java.io.*;
public class OldIOExample {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader("input.txt"));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
}
}
import java.nio.file.*;
import java.util.stream.*;
public class NIOExample {
public static void main(String[] args) throws Exception {
Stream<String> lines = Files.lines(Paths.get("input.txt"));
lines.forEach(System.out::println);
}
}
■ NIO Channels & Buffers
NIO introduced Channels, Buffers, and Selectors. Channels transfer data, Buffers store data, and Selectors manage multiple channels.
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
public class ChannelExample {
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream("input.txt");
FileChannel channel = fis.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(48);
int bytesRead = channel.read(buffer);
System.out.println("Bytes read: " + bytesRead);
channel.close();
fis.close();
}
}
■ Socket Programming
Java provides APIs for TCP and UDP socket communication.
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(5000);
Socket socket = server.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
System.out.println("Client says: " + in.readLine());
server.close();
}
}
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("localhost", 5000);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
out.println("Hello Server");
socket.close();
}
}
■ Mini Quiz – Block 5
Question Answer
Difference between I/O and NIO? I/O is stream-based & blocking; NIO is buffer-based & non-blocking.
What is a Channel in NIO? An abstraction for data transfer to and from buffers.
What does a Selector do? Manages multiple channels using a single thread.
How does Java support sockets? Using ServerSocket and Socket classes for TCP communication.
■ Block 6 – Functional & Modern Java (Java 8 → 21)
■ Lambdas & Functional Interfaces
Lambdas introduced in Java 8 enable functional programming. Functional interfaces contain a single abstract method.
import java.util.function.*;
public class LambdaDemo {
public static void main(String[] args) {
Predicate<Integer> isEven = n -> n % 2 == 0;
System.out.println(isEven.test(4)); // true
Function<String, Integer> length = s -> s.length();
System.out.println(length.apply("Hello")); // 5
}
}
■ Streams API
Streams support declarative data processing using map, filter, reduce, and collectors.
import java.util.*;
import java.util.stream.*;
public class StreamsDemo {
public static void main(String[] args) {
List<Integer> nums = Arrays.asList(1,2,3,4,5,6);
int sum = nums.stream()
.filter(n -> n % 2 == 0)
.mapToInt(Integer::intValue)
.sum();
System.out.println("Sum of evens: " + sum);
}
}
■ Optional API
Optional helps avoid NullPointerExceptions by explicitly handling absence of values.
import java.util.Optional;
public class OptionalDemo {
public static void main(String[] args) {
Optional<String> name = Optional.ofNullable(null);
System.out.println(name.orElse("Default"));
}
}
■ Modern Java Features (Java 9 → 21)
Key modern features include Modules (Java 9), var (Java 10), Records & Sealed Classes (Java 14), Pattern Matching, Switch Expressions (Java 17), and
Virtual Threads (Java 21).
public class VirtualThreadDemo {
public static void main(String[] args) throws Exception {
Thread vt = Thread.ofVirtual().start(() -> {
System.out.println("Hello from Virtual Thread");
});
vt.join();
}
}
■ Mini Quiz – Block 6
Question Answer
What is a functional interface? An interface with a single abstract method.
Difference between map() and flatMap()? map transforms each element; flatMap flattens nested structures.
What does Optional help with? Avoids NullPointerExceptions by representing absent values.
What are virtual threads? Lightweight threads introduced in Java 21, managed by the JVM.
■ Block 7 – Practical Exercises & Mini Projects
■ Project 1: Producer-Consumer with BlockingQueue
import java.util.concurrent.*;
class Producer implements Runnable {
private BlockingQueue<Integer> queue;
public Producer(BlockingQueue<Integer> q) { this.queue = q; }
public void run() {
try {
for (int i = 0; i < 5; i++) {
queue.put(i);
System.out.println("Produced: " + i);
}
} catch (InterruptedException e) { e.printStackTrace(); }
}
}
class Consumer implements Runnable {
private BlockingQueue<Integer> queue;
public Consumer(BlockingQueue<Integer> q) { this.queue = q; }
public void run() {
try {
for (int i = 0; i < 5; i++) {
System.out.println("Consumed: " + queue.take());
}
} catch (InterruptedException e) { e.printStackTrace(); }
}
}
public class ProducerConsumerDemo {
public static void main(String[] args) {
BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(10);
new Thread(new Producer(queue)).start();
new Thread(new Consumer(queue)).start();
}
}
■ Project 2: Thread-safe Singleton using Enum
enum Singleton {
INSTANCE;
public void showMessage() {
System.out.println("Hello from Singleton");
}
}
public class SingletonDemo {
public static void main(String[] args) {
Singleton s = Singleton.INSTANCE;
s.showMessage();
}
}
■ Project 3: Custom Annotation & Processor
import java.lang.annotation.*;
import java.lang.reflect.*;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface Test {}
class MyTests {
@Test
public void testMethod() {
System.out.println("Running test...");
}
}
public class AnnotationProcessorDemo {
public static void main(String[] args) throws Exception {
for (Method m : MyTests.class.getDeclaredMethods()) {
if (m.isAnnotationPresent(Test.class)) {
m.invoke(new MyTests());
}
}
}
}
■ Project 4: In-Memory Cache with WeakReference
import java.lang.ref.*;
import java.util.*;
public class CacheDemo {
private Map<String, WeakReference<String>> cache = new HashMap<>();
public void put(String key, String value) {
cache.put(key, new WeakReference<>(value));
}
public String get(String key) {
WeakReference<String> ref = cache.get(key);
return ref != null ? ref.get() : null;
}
public static void main(String[] args) {
CacheDemo cache = new CacheDemo();
cache.put("1", new String("Hello"));
System.out.println("Cache: " + cache.get("1"));
System.gc();
System.out.println("Cache after GC: " + cache.get("1"));
}
}
■ Project 5: Multithreaded Web Crawler
import java.net.*;
import java.io.*;
import java.util.concurrent.*;
class CrawlerTask implements Runnable {
private String url;
public CrawlerTask(String url) { this.url = url; }
public void run() {
try (BufferedReader in = new BufferedReader(new InputStreamReader(new URL(url).openStream()))) {
String line;
while ((line = in.readLine()) != null) {
if (line.contains("href")) System.out.println("Found link: " + line);
}
} catch (Exception e) { e.printStackTrace(); }
}
}
public class WebCrawlerDemo {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(3);
executor.submit(new CrawlerTask("http://example.com"));
executor.submit(new CrawlerTask("http://example.org"));
executor.shutdown();
}
}
■ Block 8 – Java Interview Questions & Answers
■ Core Java
Q: What is the difference between JDK, JRE, and JVM?
A: JDK (Java Development Kit) provides tools + JRE. JRE (Java Runtime Environment) provides libraries + JVM. JVM runs Java bytecode.
Q: Explain the 'final' keyword usage in Java.
A: final can be used with variables (constant), methods (cannot override), and classes (cannot inherit).
Q: Difference between equals() and == ?
A: equals() checks value equality; == checks reference equality.
Q: What are wrapper classes?
A: Classes that wrap primitive data types (int → Integer, boolean → Boolean).
■ OOP & Advanced Concepts
Q: What is method overloading vs overriding?
A: Overloading: same method name, different parameters. Overriding: subclass redefines parent method with same signature.
Q: What is the difference between abstract class and interface?
A: Abstract class can have fields + method implementations. Interface (Java 8+) can have default/static methods, mainly contracts.
Q: Explain the 'this' and 'super' keywords.
A: 'this' refers to current object, 'super' refers to immediate parent class object.
Q: What is a sealed class?
A: A class that restricts which classes can extend it (Java 14+).
■ Multithreading & Concurrency
Q: What is the difference between process and thread?
A: Process is independent execution unit with its own memory. Threads are lightweight, share process memory.
Q: Explain thread lifecycle states.
A: NEW, RUNNABLE, RUNNING, WAITING, TIMED_WAITING, BLOCKED, TERMINATED.
Q: What is a deadlock?
A: When two/more threads wait indefinitely for resources held by each other.
Q: What are synchronized blocks and methods?
A: They ensure only one thread accesses the critical section at a time.
■ JVM Internals & Memory
Q: What are JVM memory areas?
A: Heap, Stack, Method Area, PC Register, Native Method Stack.
Q: Difference between Stack and Heap?
A: Stack stores method frames and local variables. Heap stores objects accessible by all threads.
Q: Explain Garbage Collection in Java.
A: GC reclaims memory of objects no longer referenced. Algorithms: Serial, Parallel, CMS, G1, ZGC, Shenandoah.
Q: What is JIT compilation?
A: Just-In-Time compiler optimizes hot code by compiling bytecode to native code at runtime.
■ Modern Java Features
Q: What are streams in Java?
A: Streams process collections declaratively using filter-map-reduce operations.
Q: Explain Optional API.
A: Optional is a container object that may/may not contain a value. Avoids NullPointerException.
Q: What are records in Java?
A: Immutable data carrier classes with concise syntax (Java 14+).
Q: What are virtual threads?
A: Lightweight threads (Java 21) scheduled by JVM, enabling high concurrency.
■ Tricky & Common Interview Questions
Q: Can we override static methods?
A: No, they are hidden, not overridden.
Q: Can a constructor be final?
A: No, constructors cannot be inherited or overridden.
Q: What is the difference between checked and unchecked exceptions?
A: Checked: must be handled/declared. Unchecked: RuntimeException and its subclasses.
Q: Explain difference between HashMap and ConcurrentHashMap.
A: HashMap is not thread-safe, ConcurrentHashMap supports concurrent access without locking whole map.