Datasets:

File size: 51,524 Bytes
fee8509
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
{"question": "What is the difference between JDK, JRE, and JVM?", "answer": "The JVM (Java Virtual Machine) is the abstract machine that executes bytecode. The JRE (Java Runtime Environment) includes the JVM plus core libraries required to run Java applications. The JDK (Java Development Kit) contains the JRE along with development tools like compilers (javac), debuggers, and utilities needed to build Java applications."}
{"question": "Why is Java considered platform-independent?", "answer": "Java is platform-independent because of the 'Write Once, Run Anywhere' principle. Source code is compiled into bytecode (.class files), which is not tied to any specific hardware architecture. The JVM interprets this bytecode on any operating system (Windows, Linux, macOS) that has a compatible implementation, isolating the application from OS-specific details."}
{"question": "What is garbage collection in Java and how does it work?", "answer": "Garbage Collection (GC) is automatic memory management that frees up heap space by reclaiming objects that are no longer reachable. It works by identifying live references starting from GC Roots (static fields, local variables, active threads). Objects without paths to these roots are marked as dead and removed. Modern collectors like G1 or ZGC use generational hypotheses to optimize pause times."}
{"question": "What is the difference between Stack and Heap memory in Java?", "answer": "Stack memory stores primitive values and reference variables for method calls; it is thread-local and fast but limited in size. Heap memory stores actual object instances and arrays shared across all threads; it is larger but slower due to garbage collection overhead. References in stack point to objects in heap."}
{"question": "Explain the concept of immutability in Java.", "answer": "Immutability means an object's state cannot be modified after creation. In Java, String is immutable. To create an immutable class, declare fields as private final, provide no setters, ensure deep copying if holding mutable objects, and make the class final. Immutability ensures thread safety, allows safe hashing, and simplifies debugging."}
{"question": "What is the difference between == and .equals() in Java?", "answer": "The == operator compares reference identity (memory addresses) for objects, or value equality for primitives. The .equals() method is designed for logical equality comparison. For Strings, == checks if they are the same object instance, while .equals() checks if the character sequences are identical. Overriding .equals() correctly requires also overriding hashCode()."}}
{"question": "How does HashMap handle collisions in Java?", "answer": "HashMap uses chaining to resolve collisions. When two keys hash to the same bucket index, they are stored in a linked list at that bucket. Since Java 8, if a bucket's chain exceeds 8 entries and the table size is at least 64, the linked list converts to a balanced red-black tree, reducing worst-case lookup time from O(n) to O(log n)."}
{"question": "What is the contract between equals() and hashCode()?", "answer": "The contract states: 1) If two objects are equal according to equals(), their hashCode() must return the same integer. 2) If two objects have the same hashCode(), they are not necessarily equal. Violating this breaks hash-based collections like HashSet and HashMap, causing data loss or inability to retrieve elements."}
{"question": "What is autoboxing and unboxing in Java?", "answer": "Autoboxing is the automatic conversion of primitive types (int, double) to their corresponding wrapper classes (Integer, Double). Unboxing is the reverse process. While convenient, excessive boxing/unboxing can cause performance issues due to object allocation and NullPointerException risks if a null wrapper is unboxed."}
{"question": "What is the difference between ArrayList and LinkedList?", "answer": "ArrayList is backed by a dynamic array, offering O(1) random access but O(n) insertion/deletion in the middle due to shifting elements. LinkedList is backed by a doubly-linked list, offering O(1) insertion/deletion at ends/middle (if node is known) but O(n) random access. ArrayList is generally preferred for read-heavy workloads due to better cache locality."}
{"question": "What is the purpose of the final keyword in Java?", "answer": "Final prevents modification. Applied to a variable, it makes it constant (cannot be reassigned). Applied to a method, it prevents overriding in subclasses. Applied to a class, it prevents inheritance. Final enables compiler optimizations and ensures immutability contracts for threads."}
{"question": "How does Java handle concurrency with the volatile keyword?", "answer": "Volatile guarantees visibility and ordering. It ensures that changes to a variable are immediately visible to other threads (no CPU caching) and prevents instruction reordering around the volatile write/read. However, it does not guarantee atomicity for compound actions (like i++), so Atomic classes or synchronization are needed for those."}
{"question": "What is the difference between synchronized block and synchronized method?", "answer": "A synchronized method locks on the instance object (this) or class object (for static methods). A synchronized block allows specifying a particular lock object, enabling finer-grained locking. Blocks are often preferred to reduce contention by locking only the critical section rather than the entire method body."}
{"question": "What is a Deadlock in Java and how to prevent it?", "answer": "Deadlock occurs when two or more threads wait indefinitely for each other to release locks. Prevention strategies include: acquiring locks in a consistent global order, using tryLock() with timeouts, avoiding nested locks, and designing algorithms to minimize lock duration. Tools like Thread Dump analysis help detect existing deadlocks."}
{"question": "What is the ExecutorService framework used for?", "answer": "ExecutorService provides a higher-level abstraction over raw Threads. It manages a pool of worker threads, handles task submission (Runnable/Callable), and lifecycle management (shutdown). It decouples task production from execution, allowing reuse of threads and control over concurrency levels via ThreadPoolExecutor configurations."}
{"question": "What is CompletableFuture and why is it useful?", "answer": "CompletableFuture represents a future result of an asynchronous computation. It allows composing multiple async tasks sequentially or in parallel using fluent APIs (thenApply, thenCompose, allOf). Unlike Future, it supports callbacks, exception handling, and cancellation without blocking threads, making it ideal for non-blocking I/O and reactive programming."}
{"question": "What is the difference between Checked and Unchecked Exceptions?", "answer": "Checked exceptions (extend Exception) must be declared in method signatures or caught explicitly; they represent recoverable conditions (e.g., IOException). Unchecked exceptions (extend RuntimeException) do not require declaration; they represent programming errors (e.g., NullPointerException). Java favors unchecked exceptions for cleaner API design unless recovery is mandatory."}
{"question": "How does Try-with-resources work in Java?", "answer": "Try-with-resources automatically closes resources implementing AutoCloseable (like InputStream, Connection) at the end of the try block, even if an exception occurs. It eliminates verbose finally blocks and suppresses secondary exceptions thrown during closing, attaching them to the primary exception for debugging."}
{"question": "What is the role of ClassLoader in Java?", "answer": "ClassLoader loads .class files into JVM memory. It follows a delegation hierarchy: Bootstrap -> Extension -> Application. Custom ClassLoaders allow loading classes from non-standard sources (network, jars, encryption) and enable hot-swapping or modular isolation. Understanding ClassLoaders is crucial for diagnosing ClassNotFoundException or NoClassDefFoundError."}
{"question": "What is Reflection in Java and what are its drawbacks?", "answer": "Reflection allows inspecting/modifying classes, methods, and fields at runtime. Drawbacks include security restrictions, performance overhead (due to lack of JIT optimization), breaking encapsulation, and fragility against refactoring. It should be used sparingly, primarily for frameworks, serialization, or dependency injection containers."}
{"question": "What is the difference between Interface and Abstract Class?", "answer": "Abstract classes can have state (fields) and concrete methods, supporting partial implementation. Interfaces (pre-Java 8) had only abstract methods; now support default/static methods but no instance state. Classes can implement multiple interfaces but extend only one abstract class. Use interfaces for type polymorphism and capabilities; use abstract classes for code reuse among closely related types."}
{"question": "What are Default Methods in Java Interfaces?", "answer": "Introduced in Java 8, default methods allow adding new methods to interfaces without breaking existing implementations. They provide backward compatibility and enable mixin-style behavior. Conflicts arise if a class implements two interfaces with same-signature default methods, requiring explicit override resolution."}
{"question": "What is Functional Interface in Java?", "answer": "A functional interface has exactly one abstract method. Examples: Runnable, Callable, Comparator, Function<T,R>. They serve as targets for Lambda expressions and Method References. The @FunctionalInterface annotation enforces this constraint at compile time, ensuring clarity and preventing accidental addition of abstract methods."}
{"question": "How do Lambdas improve Java code?", "answer": "Lambdas provide concise syntax for anonymous inner classes implementing functional interfaces. They enable internal iteration (via Streams), pass behavior as parameters, and facilitate functional programming styles. This reduces boilerplate, improves readability, and encourages composition over inheritance."}
{"question": "What is the Stream API in Java?", "answer": "Stream API processes collections declaratively. Operations are categorized into intermediate (lazy: filter, map, sorted) and terminal (eager: collect, forEach, reduce). Streams support parallel processing easily via .parallel(). They focus on 'what' to do rather than 'how', enhancing expressiveness and potentially leveraging multi-core CPUs."}
{"question": "What is the difference between Map.reduce() and Collectors.toList()?", "answer": "reduce() combines stream elements into a single value (e.g., sum, max) using a BinaryOperator. Collectors.toList() gathers all elements into a List container. reduce() is for aggregation/folding; collect() is for transformation/grouping into new data structures. Collectors offer rich built-in strategies (groupingBy, partitioningBy)."}
{"question": "What is Optional in Java?", "answer": "Optional is a container object which may or may not contain a non-null value. It aims to eliminate NullPointerExceptions by forcing explicit handling of absence (isPresent, ifPresent, orElseThrow). It replaces nullable returns with monadic style, improving code safety and intent clarity, though misuse (e.g., Optional in fields) is discouraged."}
{"question": "What is Records in Java (JDK 16+)?", "answer": "Records are shallowly immutable data carriers. They automatically generate canonical constructors, getters (named after components), equals(), hashCode(), and toString(). Ideal for DTOs, value objects, and simple data structures, reducing boilerplate significantly compared to traditional POJOs or Lombok annotations."}
{"question": "What are Sealed Classes in Java (JDK 17+)?", "answer": "Sealed classes restrict which other classes may extend or implement them. Using permits clause, developers define closed hierarchies. This enables exhaustive pattern matching in switch statements, ensuring all subtypes are handled. Useful for domain modeling where inheritance boundaries must be strictly controlled."}
{"question": "What is Pattern Matching for instanceof?", "answer": "It allows casting within the condition check: if (obj instanceof String s). If true, s is available directly, eliminating redundant casts. Combined with Switch Expressions and Sealed Types, it facilitates algebraic data types and cleaner conditional logic without verbose boilerplate."}
{"question": "What is Switch Expression (Arrow Syntax)?", "answer": "New syntax allows switch as an expression returning a value: var result = switch(day) { case MON -> 1; default -> 0; }. It avoids fall-through bugs, requires exhaustiveness (or default), and supports yield for complex blocks. Improves readability and safety over traditional statement-switch."}
{"question": "What is Varargs in Java?", "answer": "Varargs (variable arity arguments) allow passing variable number of arguments to a method: void foo(String... args). Inside, args behaves like an array. Caution: mixing varargs with generic types can cause heap pollution warnings. Best placed last in parameter lists."}
{"question": "What is Generics Erasure?", "answer": "Generics are a compile-time feature. At runtime, type parameters are erased and replaced with bounds (Object or specified upper bound). This maintains backward compatibility with pre-generic code but prevents runtime type introspection (e.g., T.class) and creates limitations like no generic arrays."}
{"question": "What are Wildcards (? extends T / ? super T) in Generics?", "answer": "PECS rule: Producer Extends, Consumer Super. ? extends T allows reading T from collection (safe covariant). ? super T allows writing T to collection (safe contravariant). Used to increase API flexibility when accepting various subtype/supertype collections."}
{"question": "What is Type Token trick in Jackson/Gson?", "answer": "Due to erasure, generic types like List<String> lose info at runtime. Libraries use TypeToken or ParameterizedTypeReference to capture full generic signature anonymously, preserving type info for deserialization/serialization of complex nested generics."}
{"question": "What is Maven vs Gradle?", "answer": "Maven uses XML (pom.xml), convention-over-configuration, strict lifecycle phases. Highly stable, large ecosystem. Gradle uses Groovy/Kotlin DSL, imperative/scripting approach, incremental builds, faster performance. Gradle offers more flexibility/customization; Maven offers simplicity/predictability."}
{"question": "What is Dependency Injection (DI)?", "answer": "DI is a design pattern where dependencies are provided externally rather than created internally. Facilitates loose coupling, testability (mocking), and configurability. Implemented manually or via frameworks like Spring/Guice. Constructor injection is preferred for immutability and mandatory deps."}
{"question": "What is Inversion of Control (IoC)?", "answer": "IoC flips control flow: framework calls user code, not vice versa. DI is a form of IoC. Container manages object lifecycle/wiring. Decouples component creation from usage, centralizing configuration and promoting modularity."}
{"question": "What is Spring Bean Scope?", "answer": "Singleton (default): one instance per container. Prototype: new instance per request. Request/Session/Application/WebSocket: scoped to HTTP context. Choosing correct scope impacts memory footprint and thread safety (singletons must be stateless)."}}
{"question": "What is @Autowired in Spring?", "answer": "Annotation marking dependency for auto-injection by Spring container. Can be applied to fields, setters, or constructors. Constructor injection recommended for required deps (fail-fast, immutability). Field injection discouraged (harder testing, hides dependencies)."}
{"question": "What is Component Scan in Spring?", "answer": "Mechanism detecting annotated classes (@Component, @Service, @Repository, @Controller) in package hierarchy. Registers them as beans in ApplicationContext. Configured via @ComponentScan(basePackages=...). Essential for wiring dependencies automatically."}
{"question": "What is Spring Boot Auto-Configuration?", "answer": "Spring Boot inspects classpath, registered beans, and property settings to configure application automatically. Reduces boilerplate (e.g., embedded Tomcat, DataSource). Based on @Conditional annotations. Overrideable via properties or explicit bean definitions."}
{"question": "What is Starter POM in Spring Boot?", "answer": "Predefined dependency bundles (spring-boot-starter-web, data-jpa). Simplify build config by pulling transitively required libs. Version-managed by BOM (Bill of Materials). Ensure compatible library versions without manual alignment."}
{"question": "What is Actuator in Spring Boot?", "answer": "Production-ready endpoints exposing metrics, health checks, env vars, logs, mappings. Secured by default. Integrates with Prometheus/Grafana. Vital for observability, monitoring app status, and troubleshooting deployed services."}
{"question": "What is Spring MVC DispatcherServlet?", "answer": "Front Controller pattern implementation. Receives all HTTP requests, delegates to HandlerMapping, invokes Controller, resolves View, renders response. Central orchestrator separating concerns (routing, business logic, presentation)."}
{"question": "What is @RestController vs @Controller?", "answer": "@Controller returns view names (HTML/JSP). @RestController implies @ResponseBody on all methods, serializing return objects directly to JSON/XML. Standard for REST APIs. Avoids needing @ResponseBody on every method."}
{"question": "What is PathVariable vs RequestParam?", "answer": "@PathVariable extracts URI segment ({id}). @RequestParam extracts query string param (?page=1). PathVariables identify resources; RequestParams modify/filter/search results. Both bind dynamically to method args."}
{"question": "What is Global Exception Handling in Spring?", "answer": "@ControllerAdvice/@RestControllerAdvice intercepts exceptions globally. @ExceptionHandler maps specific exception types to HTTP responses (status codes, bodies). Centralizes error formatting, logging, and mapping domain errors to API contracts."}
{"question": "What is Spring Data JPA?", "answer": "Abstraction layer over JPA/Hibernate. Generates DAO implementations from interfaces extending Repository. Supports derived queries (findByEmail), JPQL, Native SQL. Manages EntityManager transactions, persistence context, and entity lifecycle."}
{"question": "What is N+1 Problem in Hibernate/JPA?", "answer": "Fetching parent entities triggers separate queries for each child association. Causes performance degradation. Solutions: Join Fetch (@FetchType.EAGER or JPQL JOIN FETCH), Batch Size, Entity Graphs, or DTO projections to load only needed fields."}
{"question": "What is LazyInitializationException?", "answer": "Thrown when accessing lazy-loaded associations outside active transaction/session. Persistence context detached. Fixes: Keep transaction open longer (anti-pattern), use Join Fetch, initialize proxies explicitly, or switch to EAGER (carefully)."}
{"question": "What is Optimistic Locking in JPA?", "answer": "Uses @Version field. Checks version mismatch before update. Throws OptimisticLockException if concurrent modification detected. Suitable for low-contention scenarios. Avoids database row locks, improving scalability."}
{"question": "What is Pessimistic Locking in JPA?", "answer": "Acquires exclusive DB lock on read/update. Prevents others modifying until released. Uses SELECT FOR UPDATE. High consistency but poor throughput/concurrency. Reserved for critical financial/inventory operations."}
{"question": "What is Transaction Propagation REQUIRED vs REQUIRES_NEW?", "answer": "REQUIRED: Joins existing tx or starts new. Rolls back together. REQUIRES_NEW: Suspends current, starts independent tx. Commits/Rollbacks separately. Used for audit logs or side effects that must persist regardless of main tx outcome."}
{"question": "What is Isolation Level in JDBC/Spring?", "answer": "Defines visibility of concurrent changes. READ_UNCOMMITTED (dirty reads), READ_COMMITTED (non-repeatable), REPEATABLE_READ (phantom reads possible), SERIALIZABLE (full isolation). Higher isolation = stricter consistency + lower performance. Default usually READ_COMMITTED."}
{"question": "What is Flyway/Liquibase used for?", "answer": "Database migration tools. Track schema changes via versioned scripts (SQL/XML). Apply incrementally to environments (dev/test/prod). Ensures reproducible deployments, rollback capability, and team coordination on DB structure evolution."}
{"question": "What is Unit Testing vs Integration Testing?", "answer": "Unit tests isolated classes/methods (mock deps). Fast, deterministic. Integration tests verify interactions between components/DB/API. Slower, realistic. Both essential: Units catch logic errors; Integrations catch wiring/config/schema mismatches."}
{"question": "What is Mockito used for?", "answer": "Mocking framework for Java. Creates fake objects/stubs/spies. Controls inputs/outputs, verifies interactions (calledOnce()), ignores irrelevant details. Enables pure unit testing without real DB/network dependencies."}
{"question": "What is Testcontainers?", "answer": "Library spinning up disposable Docker containers (Postgres, Kafka) for integration tests. Provides real infrastructure fidelity without mocking DB quirks. Cleans up automatically. Bridges gap between unit mocks and prod environments."}
{"question": "What is JaCoCo?", "answer": "Code coverage tool. Instruments bytecode to track executed lines/branches/methods. Generates reports (HTML/XML). Helps identify untested paths. Metric quality indicator, not correctness proof. High coverage doesn't guarantee bug-free code."}
{"question": "What is SonarQube?", "answer": "Static Analysis Platform. Detects bugs, vulnerabilities, code smells, duplications, complexity. Enforces coding standards/rules. Continuous inspection pipeline gatekeeper. Technical debt visualization. Critical for maintaining long-term code health."}
{"question": "What is SOLID principles in Java?", "answer": "Single Responsibility, Open/Closed, Liskov Substitution, Interface Segregation, Dependency Inversion. Guide maintainable/scalable OO design. Reduce coupling, enhance cohesion. Foundation for clean architecture patterns (Hexagonal/Clean Arch)."}
{"question": "What is Design Pattern Strategy?", "answer": "Encapsulates interchangeable behaviors/algorithms behind common interface. Client selects strategy at runtime. Promotes Open/Closed principle. Example: PaymentProcessor (CreditCardStrategy, PayPalStrategy). Avoids massive if/else chains."}
{"question": "What is Design Pattern Observer?", "answer": "One-to-many dependency. Subject notifies Observers on state change. Decouples publisher/subscriber. Used in event buses, UI updates, reactive streams. Java Swing/AWT historically used it; modern apps often use RxJava/Reactor."}
{"question": "What is Design Pattern Factory Method?", "answer": "Delegates instantiation to subclasses. Defines interface for creating objects, lets subclasses alter type. Encapsulates creation logic. Useful when exact type unknown at compile time or varies by environment/config."}
{"question": "What is Singleton Pattern pitfalls?", "answer": "Thread-safety requires synchronization/volatile. Hard to mock/test. Global state violates SRP. Breaks encapsulation. Often anti-pattern. Prefer DI container managed singletons over manual static holders."}
{"question": "What is Builder Pattern?", "answer": "Constructs complex objects step-by-step. Fluent API. Handles optional params/immutability. Avoids telescoping constructors. Common in Java SDKs (StringBuilder, HttpClient). Enhances readability for configs/entities."}
{"question": "What is Adapter Pattern?", "answer": "Converts interface of class into another expected by client. Makes incompatible APIs work together. Wraps legacy/third-party code. Allows integration without modifying source. Key for gradual migrations/refactoring."}
{"question": "What is Decorator Pattern?", "answer": "Adds responsibilities dynamically at runtime. Wraps base object with decorators. Alternative to subclass explosion. Preserves open/closed. Example: Java IO streams (BufferedInputStream wrapping FileInputStream)."}
{"question": "What is Proxy Pattern?", "answer": "Controls access to target object. Adds indirection. Used for lazy init, remote invocation, security/access control, caching. Spring AOP uses proxies (CGLIB/JDK Dynamic) for cross-cutting concerns like transactions/logging."}
{"question": "What is Chain of Responsibility?", "answer": "Passes request along handler chain until processed. Decouples sender/receiver. Flexible add/remove handlers. Example: Servlet Filters, Logging appenders, Exception handling layers."}
{"question": "What is Command Pattern?", "answer": "Encapsulates action as object. Parameterizes clients with different queues/logs/undo. Separates invoker from receiver. Enables macro commands, transactional undo/redo, async execution."}
{"question": "What is Template Method Pattern?", "answer": "Defines skeleton algorithm in superclass hook methods. Subclasses override steps. Inverts control (Hollywood Principle: Don't call us, we'll call you). Enforces structure while allowing customization. Common in frameworks."}
{"question": "What is Null Object Pattern?", "answer": "Provides inert implementation instead of null. Eliminates null checks. Simplifies client code. Safe defaults. Example: Collections.emptyList(), Optional.empty(). Reduces defensive programming noise."}
{"question": "What is Immutable Object benefits?", "answer": "Thread-safe (no sync needed). Hashable (stable hashCode). Cacheable. Easy reasoning/debugging. Fail-fast on mutation attempts. Preferred for value types, configs, keys. Cost: Creation overhead/cloning."}
{"question": "What is Defensive Copying?", "answer": "Cloning mutable inputs/outputs to prevent external modification affecting internal state. Crucial for immutability guarantees. Performance trade-off. Use shallow vs deep copy wisely based on object graph complexity."}
{"question": "What is Serialization in Java?", "answer": "Converting object state to byte stream (persist/transmit). Serializable interface. Risks: Security holes, versioning hell, fragile format. Alternatives: JSON (Jackson), Protobuf, Avro. Safer, language-neutral, evolvable."}
{"question": "What is Transient keyword?", "answer": "Marks field excluded from serialization. Used for sensitive data (passwords), cached values, or non-persistent state. Re-initialized to default upon deserialization. Explicit opt-out from persistence."}
{"question": "What is serialVersionUID?", "answer": "Version identifier for Serialized class. Mismatch throws InvalidClassException. Auto-generated unstable across compilers. Always define explicitly (private static final long) to control compatibility/versioning strategy."}
{"question": "What is Cloneable interface?", "answer": "Marker interface permitting clone() method. Shallow copy by default. Deep copy requires manual implementation. Fragile, confusing semantics. Often avoided in favor of copy constructors or builder copies."}
{"question": "What is EnumSet/EnumMap?", "answer": "Specialized collections for enums. Bit-vector representation. Extremely fast/memory efficient. Type-safe key/value constraints. Ideal for flags, categories, finite state machines. Avoids string/int magic numbers."}
{"question": "What is BitSet?", "answer": "Space-efficient vector of booleans. Dynamic sizing. Fast bitwise ops (AND/OR/XOR). Used for bloom filters, presence checks, huge sparse matrices. Lower memory than boolean[] or Set<Integer>."}
{"question": "What is ConcurrentHashMap?", "answer": "Thread-safe map. Segment locking (pre-Java 8) or CAS/node locking (Java 8+). High concurrency reads/writes. Non-blocking iterators. Weakly consistent snapshots. Preferred over Hashtable/synchronizedMap for scalable caches."}
{"question": "What is CopyOnWriteArrayList?", "answer": "List mutating via fresh copy on write. Reads lock-free/fast. Writes expensive/O(n). Ideal for listener/event registries where reads >> writes. Snapshot iteration stability guaranteed."}
{"question": "What is BlockingQueue?", "answer": "Queue supporting put/take waiting when empty/full. Producer-consumer buffer. Implementations: ArrayBlockingQueue (bounded), LinkedBlockingQueue (unbounded/linkedList), PriorityBlockingQueue. Core building block for thread pools/task schedulers."}
{"question": "What is Semaphore?", "answer": "Counting permit controller. Limits concurrent access to resource pool. acquire()/release(). Binary semaphore = mutex. Fairness configurable. Used for rate limiting, connection pooling, resource throttling."}
{"question": "What is CountDownLatch?", "answer": "Sync aid: one/more threads wait until N events complete. decrementCount(). await(). One-shot reset impossible. Useful for startup gates, parallel task completion barriers. CyclicBarrier alternative allows resetting/reuse."}
{"question": "What is Phaser?", "answer": "Flexible barrier/registrar. Parties arrive/deregister dynamically. Multi-phase synchronization. Advanced replacement for latch/barrier. Complex but powerful for iterative concurrent algorithms/phases."}
{"question": "What is ForkJoinPool?", "answer": "Work-stealing executor for recursive divide-and-conquer tasks. Split big job into subjobs, merge results. Optimal CPU utilization. Background thread stealing idle peers' work. Powers parallelStream()."}
{"question": "What is ParallelStream?", "answer": "Stream executing operations concurrently via ForkJoinPool.commonPool(). Speedup for CPU-intensive, independent element processing. Caveats: Shared pool contention, unordered results, side-effect dangers, boxing overhead."}
{"question": "What is Project Reactor / RxJava?", "answer": "Reactive Streams implementations. Async event/data streams. Backpressure support. Operators: map, flatMap, zip, combineLatest. Non-blocking, composable, resilient. Fits microservices/streaming/IoT. Steep learning curve vs Imperative."}
{"question": "What is Mono/Flux in Reactor?", "answer": "Mono: 0..1 emission. Flux: 0..N emissions. Reactive publishers. Subscribe triggers execution. Cold vs Hot streams. Error/completion signals. Basis for WebFlux/Spring Reactive stack."}
{"question": "What is Backpressure?", "answer": "Flow control mechanism. Slow consumer signals producer to throttle. Prevents buffer overflow/OOM. Built into Reactive Streams spec. Manual handling in traditional IO risky. Essential for robust async systems."}
{"question": "What is GraalVM Native Image?", "answer": "Ahead-of-Time (AOT) compilation to binary. Instant startup (<ms), low RAM. No JIT warmup. Limited reflection/dynamic features (requires metadata hints). Ideal for serverless/FaaS/cloud-native microservices."}
{"question": "What is Quarkus/Micronaut?", "answer": "Cloud-Native Java frameworks. Build-time DI/configuration (vs runtime scan). CDI/AOP integrated. Optimized for containers/serverless. Faster boot/lower memory than traditional Spring. Embrace GraalVM native goals."}
{"question": "What is Jakarta EE vs Java EE?", "answer": "Java EE renamed to Jakarta EE after Oracle transfer to Eclipse Foundation. Namespace changed javax.* to jakarta.*. Breaking change requiring migration. Continues enterprise specs (Servlet, EJB, JPA, CDI)."}
{"question": "What is MicroProfile?", "answer": "Lightweight spec suite for microservices. Config, Health, Metrics, Fault Tolerance, JWT, OpenTracing. Vendor-neutral alternatives to heavy Java EE parts. Complements Quarkus/OpenLiberty/Payara."}
{"question": "What is Service Mesh (Istio/Linkerd)?", "answer": "Infra layer handling service-to-service comm. Sidecar proxies manage mTLS, retries, timeouts, telemetry, traffic splitting. Offloads network concerns from app code. Polyglot support. Complexity trade-off."}
{"question": "What is gRPC?", "answer": "High-performance RPC framework. HTTP/2 transport. Protobuf IDL. Strong typing, streaming, multiplexing. Lower latency/bandwidth than REST/JSON. Codegen stubs. Great for internal microservice chatty comms."}
{"question": "What is Protocol Buffers?", "answer": "Language-neutral structured data serialization. Compact binary format. Schema evolution (backward/forward compat). Generated parsers. Faster/smaller than JSON/XML. Standard for gRPC/messages."}
{"question": "What is Avro?", "answer": "Serialization framework with schema registry. JSON-like schemas. Binary encoding. Excellent for Kafka/events. Schema enforcement/validation. Evolvable. Big Data ecosystem standard."}
{"question": "What is Kafka Connect?", "answer": "Scalable streaming data integration. Source/Sink connectors bridge Kafka <-> DBs/files/apps. Distributed, fault-tolerant. REST config. Prebuilt plugins (JDBC, S3). Eliminates custom glue code for ETL/ELT."}
{"question": "What is Kafka Streams?", "answer": "Client library for stateful stream processing. Topology DSL (KTable/KStream). Local state stores (RocksDB). Exactly-once semantics. Lightweight alternative to Flink/Spark for moderate scale/stateful logic."}
{"question": "What is ksqlDB?", "answer": "SQL engine atop Kafka Streams. Declarative stream/table queries. Materialized views. Interactive CLI. Low-code analytics/alerting on real-time data. Bridges gap between devs and analysts."}
{"question": "What is Elasticsearch?", "answer": "Distributed search/analytics engine. Lucene backend. JSON docs. Near-real-time indexing/querying. Aggregations. Log storage (ELK). Vector search (kNN). Scale horizontally. Tuning shards/mappings critical."}
{"question": "What is Kibana?", "answer": "Visualization/dashboarding tool for Elasticsearch. Explore data, build charts/maps/alerts. Dev tools console. Management UI. Part of Elastic Stack. User-friendly frontend for ES power."}
{"question": "What is Logstash?", "answer": "Server-side data processing pipeline. Ingest, transform, enrich logs/metrics. Plugins (grok, mutate, filter). Output to ES/file/db. Heavyweight agent. Beats (Filebeat) lighter alternative for shipping."}
{"question": "What is Filebeat?", "answer": "Lightweight log shipper. Tail files/stdin. Harvester/input modules. Outputs to Logstash/ES/Redis/Kafka. Resource efficient. Reliable delivery (spooling). Standard for host log collection."}
{"question": "What is Prometheus?", "answer": "Time-series database & monitoring system. Pull model scraping metrics endpoints. PromQL query language. Alertmanager routing. Grafana viz. CNCF graduated. De facto cloud-native monitoring standard."}
{"question": "What is Grafana?", "answer": "Observability dashboarding platform. Visualize metrics/logs/traces from diverse sources (Prom, ES, CloudWatch). Alerts, annotations, templating. Plugin ecosystem. Team collaboration hub for ops/devs."}
{"question": "What is OpenTelemetry?", "answer": "Vendor-neutral observability framework. Standards/APIs/SDKs for traces, metrics, logs. Collector pipelines export to backends (Jaeger, Zipkin, OTLP). Unified instrumentation replacing proprietary agents. Future-proof telemetry."}
{"question": "What is Jaeger/Zipkin?", "answer": "Distributed tracing systems. Collect/span storage/UI. Visualize request flows across microservices. Identify bottlenecks/errors. Jaeger CNCF, Zipkin Twitter-origin. Essential for debugging complex architectures."}
{"question": "What is Chaos Engineering?", "answer": "Proactive resilience testing. Inject failures (kill pods, latency, errors) in prod/staging. Validate system withstands disruptions. Tools: Gremlin, LitmusChaos, Chaos Monkey. Shift-left reliability culture."}
{"question": "What is Feature Flags?", "answer": "Runtime toggles enabling/disabling code paths. Gradual rollouts, A/B testing, kill switches. Separate deploy/release. Tools: LaunchDarkly, Unleash, Flagsmith. Reduce risk, accelerate experimentation velocity."}
{"question": "What is Trunk-Based Development?", "answer": "Short-lived branches merging frequently to mainline. Small commits, CI gates, feature flags hide incomplete work. Contrasts Git Flow. Enables continuous integration/delivery truly. Requires strong discipline/tests."}
{"question": "What is Monorepo?", "answer": "Single repo hosting multiple projects/libs. Atomic changes across boundaries. Shared tooling/deps. Tools: Nx, Turborepo, Bazel, Git. Manage complexity at scale. Trade-off: Repo size/history noise."}
{"question": "What is Semantic Versioning (SemVer)?", "answer": "MAJOR.MINOR.PATCH scheme. Breaking changes bump MAJOR. New features MINOR. Bug fixes PATCH. Communicate upgrade impact clearly. Tooling automation relies on predictable version increments."}
{"question": "What is SBOM (Software Bill of Materials)?", "answer": "Inventory of components/licenses/vulnerabilities in software artifact. CycloneDX/SPDX formats. Supply chain transparency/security compliance. Required by US EO/executive orders. Automate generation in CI/CD."}
{"question": "What is Zero Trust Architecture?", "answer": "Never trust, always verify. Identity-centric security. Micro-segmentation. Least privilege access. Continuous validation. Moves beyond perimeter defense. Critical for cloud/hybrid distributed systems."}
{"question": "What is Secrets Management?", "answer": "Centralized secure storage/retrieval of credentials/keys/tokens. Vault, AWS Secrets Manager, Azure Key Vault. Encryption at rest/transit. Audit trails, rotation policies. Eliminate hardcoded secrets in repos/configs."}
{"question": "What is OIDC vs OAuth2?", "answer": "OAuth2: Authorization framework (access tokens). OIDC: Identity layer atop OAuth2 (ID tokens, userinfo endpoint). Authentication vs Authorization distinction blurred but clarified. OIDC adds standardized claims/profiles."}
{"question": "What is JWT Structure?", "answer": "Header.Payload.Signature. Base64Url encoded JSON segments. HMAC/RSA signing. Stateless auth carrier. Contains exp, iss, aud, sub, scopes. Verify signature + claims validity. Short TTL mitigation for theft."}
{"question": "What is Refresh Token Rotation?", "answer": "Security enhancement for OAuth. Issue new refresh token on each use, invalidate old. Detect replay attacks/theft. Force re-auth if stolen token reused. Balance UX friction vs security posture."}
{"question": "What is Passkey/WebAuthn?", "answer": "Passwordless authentication standard. Public-key crypto device-bound. Biometrics/PIN unlock private key. Phishing-resistant. Seamless UX. Future replacement for passwords/MFA SMS. Browser/OS native support growing."}
{"question": "What is Cryptography Basics in Java?", "answer": "javax.crypto/java.security APIs. AES-GCM (encryption/auth), SHA-256 (hashing), RSA/ECC (signing/key exchange). SecureRandom for entropy. Keystores/truststores. Never roll own crypto; use vetted libs/providers."}
{"question": "What is Input Validation?", "answer": "Sanitize/check external data boundaries. Whitelist > Blacklist. Length/type/format/range checks. Prevent injection (SQLi, XSS), DoS, logic abuse. Fail closed. Centralized validators/filters preferable to scattered checks."}
{"question": "What is SQL Injection prevention?", "answer": "Parameterized queries/prepared statements ONLY. Bind variables separately from SQL text. ORM abstractions help but misused HQL/native queries vulnerable. Escape chars insufficient alone. Least privilege DB users essential backup."}
{"question": "What is XSS prevention?", "answer": "Context-aware output encoding. HTML entity encode (&lt;), JS escape, URL encode. CSP headers restrict script sources. Sanitize rich text inputs (DOMPurify). HttpOnly cookies block JS access. Defense-in-depth required."}
{"question": "What is CSRF protection?", "answer": "Anti-forgery tokens synced session/request. SameSite cookie attributes (Strict/Lax). Origin/Referer header validation. Double-submit cookie pattern. State-changing POSTs protected. GET idempotent ideally."}
{"question": "What is Rate Limiting strategies?", "answer": "Token Bucket/Leaky Bucket/Sliding Window. Per-user/IP/API-key quotas. Edge/WAF/App-layer enforcement. 429 Too Many Requests + Retry-After headers. Protect availability/resources. Tiered limits (premium/free)."}
{"question": "What is Circuit Breaker pattern?", "answer": "Detect failing dependencies quickly. OPEN state rejects calls fast-fail. HALF_OPEN probes recovery. CLOSED normal operation. Thresholds/timeouts tune sensitivity. Resilience4j/Hystrix impls. Prevent cascade failures/resource exhaustion."}
{"question": "What is Bulkhead pattern?", "answer": "Isolate resources per component/function. Thread/connection pools capped individually. Failure in Module A doesn't starve Module B. Limits blast radius. Complements circuit breakers for granular fault tolerance."}
{"question": "What is Retry with Exponential Backoff?", "answer": "Transient failure recovery. Increase delay exponentially (1s, 2s, 4s...) + jitter randomness. Cap max attempts. Idempotent ops only. Avoid thundering herd. Combine with circuit breaker for smart gating."}
{"question": "What is Timeout configuration?", "answer": "Bound latency expectations. Connect/Read/Write/Overall timeouts. Client/server sides aligned. Prevent hanging threads/resources. Cascading timeouts tighter downstream/upstream. Critical for SLAs/user experience."}
{"question": "What is Graceful Shutdown?", "answer": "Stop accepting new reqs. Finish inflight requests/tasks. Close connections cleanly. Release resources. Signal handling (SIGTERM). Kubernetes terminationGracePeriodSeconds. Avoid abrupt kills/data corruption/orphaned threads."}
{"question": "What is Health Check endpoints?", "answer": "/health/live (liveness: process alive?), /health/ready (readiness: deps connected?). Orchestration probes restart/removal decisions. External LB routing gates. Detailed subservices status optional/secured. Simple boolean fast responses preferred."}
{"question": "What is Readiness Probe?", "answer": "Indicates app ready to accept traffic. Dependencies loaded/cache warmed/DB connected. K8s waits before sending pods to service endpoints. Prevents premature overload/startup errors hitting users. Distinct from liveness."}
{"question": "What is Liveness Probe?", "answer": "Indicates app running normally. Not stuck/deadlocked/OOM-hunting. Restarts container if fails repeatedly. Ignores transient slowness/high load (unless fatal). Focuses on internal state integrity vs external connectivity."}
{"question": "What is Startup Probe?", "answer": "For slow-initializing apps. Delays liveness/readiness checks until success. Prevents false-positive restarts during lengthy boot (migration/cache fill). Success threshold defines readiness window start. Optimizes cold-start reliability."}
{"question": "What is Horizontal Pod Autoscaler (HPA)?", "answer": "K8s scales replica count based on metrics (CPU/RAM/custom). Target utilization %. Min/max bounds. Stabilization windows prevent flapping. Custom metrics adapter needed for RPS/queue depth. Works with Cluster Autoscaler for nodes."}
{"question": "What is Vertical Pod Autoscaler (VPA)?", "answer": "Adjusts resource requests/limits per pod. Recommends optimal sizes based on historical usage. Updates manifests or live (updateMode). Complement HPA (scale out vs up/right-size). Risky for stateful/singletons without careful tuning."}
{"question": "What is DaemonSet?", "answer": "Ensures one pod copy runs on all (or selected) nodes. System daemons/log shippers/monitoring agents. Node affinity/taints control placement. Automatic rescheduling on node reboot/addition. Infrastructure-level workload management."}
{"question": "What is StatefulSet?", "answer": "Manages ordered deployment/scaling/storage for stateful apps (DBs/ZooKeeper). Stable network IDs/hostnames. Persistent volume claims per replica ordinal. Ordered rolling updates/shutdowns. Guarantees uniqueness/ordering unlike Deployments."}
{"question": "What is ConfigMap/Secret?", "answer": "Externalize configuration/env vars. ConfigMap plaintext/non-sensitive. Secret base64-encoded/sensitive (mounted tmpfs/encrypted etcd). Inject via env/volume/command-line args. Update propagation varies (restart vs reload). Decouple image from config."}
{"question": "What is Helm Chart?", "answer": "Package manager/template engine for K8s apps. YAML templates + values.yaml overrides. Releases track installations/upgrades/rollbacks. Repos distribute charts. Simplify complex manifest management/versioning/diffing across environments."}
{"question": "What is Operator pattern?", "answer": "Extend K8s API with custom controllers/resources. Encode operational knowledge/automation (backup/restore/upgrade/failover). CRDs define domain models. Controllers reconcile desired vs actual state. Self-driving infrastructure/software."}
{"question": "What is Service Mesh sidecar?", "answer": "Proxy container alongside app pod. Intercepts ingress/egress traffic. Handles mTLS/retries/timeouts/loadbalancing/observability transparently. Envoy commonly used. Control plane configures data plane. Abstract network complexities."}
{"question": "What is Mutual TLS (mTLS)?", "answer": "Both client/server authenticate certs. Encrypt channel + verify identities. Zero-trust foundation. Certificate provisioning/rotation automated via cert-manager/service mesh. Prevents spoofing/eavesdropping. Mandatory for secure internal east-west traffic."}
{"question": "What is NetworkPolicy?", "answer": "Pod-level firewall rules. Allow/deny ingress/egress by labels/IPs/ports/namespaces. Default deny-all best practice. Enforce segmentation/least privilege. CNI plugin dependent (Calico/Cilium). Basic tenant/isolation controls."}
{"question": "What is RBAC in Kubernetes?", "answer": "Role-Based Access Control. Roles/ClusterRoles define permissions (verbs/resources/apiGroups). RoleBindings/ClusterRoleBindings assign subjects (users/groups/SAs). Granular authorization. Integrate with OIDC/LDAP providers. Auditing enabled."}
{"question": "What is Admission Controller?", "answer": "Intercept mutating/validating requests pre-persistence. Enforce policies (label injection, resource quotas, security contexts, naming conventions). OPA/Gatekeeper/Common Gate examples. Guardrails prevent bad configs entering cluster. Policy-as-code enforcement."}
{"question": "What is Etcd?", "answer": "Consistent distributed key-value store backing K8s state. Raft consensus protocol. Watch mechanisms for changes. Snapshots/backups critical disaster recovery. ACL/TLS secured. Heart of cluster brain/knowledge."}
{"question": "What is kubelet?", "answer": "Node agent managing pod containers/images/volumes/network/plugins. Reports status to API server. Executes scheduler assignments. Handles local storage/certificates. CRI/CNI/CSI integrations. Worker node supervisor daemon."}
{"question": "What is kube-proxy?", "answer": "Maintains network rules on nodes. Implements Service VIP->Pod IP translation/loadbalancing. iptables/ipvs modes. Kernel-space packet forwarding optimization. Session affinity/sticky IPs supported. Traffic steering fabric component."}
{"question": "What is Scheduler?", "answer": "Assigns pending pods to suitable nodes. Filters (feasibility) + Scores (priority/optimal fit). Affinity/anti-affinity/taints/tolerations/resources/topology spread constraints. Pluggable profiles/frameworks. Balances load/utilization/resilience requirements."}
{"question": "What is API Server?", "answer": "Frontend/control plane hub. RESTful CRUD operations on resources. AuthN/AuthZ/admission/webhooks. Watch streams for clients/controllers. Single entry point validating/persisting to etcd. Scalability bottleneck mitigated via caching/partitions."}
{"question": "What is Cloud Provider Interface (CCM)?", "answer": "Out-of-tree controller integrating vendor specifics (LB creation/routes/zones/instances). Abstracts infra differences AWS/Azure/GCP/OpenStack. Enables portable cluster logic. Manages node lifecycle/cloud metadata sync. Modular extensibility."}
{"question": "What is CSI (Container Storage Interface)?", "answer": "Standard plugin API for storage provisioning/mounting/expansion/snapshots. Decouple drivers from K8s core. Dynamic PV/PVC binding. Volume topology awareness. Support NFS/iSCSI/block/object clouds uniformly. Portable storage abstraction."}
{"question": "What is CNI (Container Network Interface)?", "answer": "Standard plugin API for configuring network namespaces/interfaces/routes/firewalls. IPAM integration. Overlay/underlay/baremetal support. Calico/Cilium/Flannel examples. Plug-and-play networking stack selection. Isolates pod connectivity concerns."}
{"question": "What is OCI (Open Container Initiative)?", "answer": "Standards for image format/runtime spec. Interoperability Docker/Podman/containerd/CRI-O. Content-addressable layers/artifacts. Digest verification. Reproducible builds/signatures. Foundation of container ecosystem neutrality/portability."}
{"question": "What is Distroless Image?", "answer": "Minimal base containing only app binaries/deps/libraries. No shell/package managers/os utils. Reduced attack surface/size/vulnerabilities. Google-maintained variants. Static linking often required. Production-hardened minimalism trend."}
{"question": "What is Multi-stage Build?", "answer": "Dockerfile stages compile/build in fat env, copy artifacts to slim runtime. Exclude build tools/source/secrets from final image. Smaller/faster/secure outputs. Cache optimization per stage. Standard practice for efficient packaging."}
{"question": "What is Layer Caching?", "answer": "Reuse unchanged filesystem layers between builds. Order instructions least->most frequent change. COPY src AFTER npm install maximizes cache hits. Invalidate only affected subtrees. Dramatic CI speed improvements via incremental rebuilds."}
{"question": "What is Rootless Containers?", "answer": "Run containers without root privileges/host namespace sharing. User namespaces map UID/GID. Enhanced security isolation. Podman/rootkit examples. Avoid privileged escalation vectors. Compliance friendly/default safer posture adoption rising."}
{"question": "What is Seccomp/AppArmor/SELinux?", "answer": "Linux kernel security modules restricting syscalls/macros/policies. Drop unnecessary capabilities. Constrain file/process/network access. Profile-based whitelisting/blacklisting. Harden runtime containment against escapes/exploits. Defense-in-depth mandatory."}
{"question": "What is Capability Dropping?", "answer": "Remove unused Linux capabilities (NET_ADMIN/SYS_PTRACE/etc.) from container processes. Principle of least privilege. Mitigate exploit impact severity. Explicit grant needed exceptions. Essential hardening step post-root removal efforts."}
{"question": "What is Immutable Infrastructure?", "answer": "Servers/devices treated replace-not-modify. Bake AMIs/images/configs ahead time. Deploy swap whole units. Rollback trivial redeploy previous version. Drift elimination/reproducibility/environments parity. Pipeline-driven consistency guarantee."}
{"question": "What is GitOps?", "answer": "Git repo sole source truth declaring desired state. Agents (ArgoCD/Flux) sync clusters autonomously. PR reviews/approvals gate deployments. Audit trail/history inherent. Declarative infra/code convergence automation. Human-readable ops workflow shift."}