Pick a topic — languages & databases — 100+ questions and answers in the center column.
Java
JVM, OOP, collections, concurrency, memory.
102 questions
Question 1
JVM runs bytecode; JRE is JVM + libraries to run apps; JDK adds compiler and dev tools.
Example code
class H { public static void main(String[] a) { System.out.println("Java"); } }Question 2
Source compiles to bytecode; JVMs for each OS execute it with JIT compilation.
Example code
// javac Main.java && java MainQuestion 3
Entry point: public access, static (no instance), void return, String[] args for CLI.
Example code
public static void main(String[] args) { System.out.println(args.length); }Question 4
Encapsulation, abstraction, inheritance, polymorphism—know a Java example for each.
Example code
// encapsulation: private fields + gettersQuestion 5
Class is blueprint; object is instance in memory with its own field values.
Example code
class Box { int v; Box(int v) { this.v = v; } }Question 6
Interface: contract, often no state (Java 8+ default methods). Abstract class: shared fields/partial implementation. Implement many interfaces; extend one class.
Example code
interface Drawable { void draw(); }Question 7
== compares references for objects (identity) and values for primitives. equals() is logical equality—override with hashCode for hash maps.
Example code
System.out.println(("a" == "a") + " " + new String("a").equals("a"));Question 8
Strings can't change; operations return new instances—safe for sharing and string pool.
Example code
String s = "hi"; // immutableQuestion 9
Both mutable char sequences; StringBuffer is synchronized, StringBuilder faster single-threaded.
Example code
StringBuilder sb = new StringBuilder(); sb.append("x");Question 10
ArrayList: fast random access, slower middle inserts. LinkedList: fast inserts with iterators, slow random access.
Example code
List<Integer> a = new ArrayList<>(); a.add(1);Question 11
Buckets by hashCode; equals resolves collisions; resize when load factor exceeded—average O(1) get/put.
Example code
Map<String, Integer> m = new HashMap<>(); m.put("a", 1);Question 12
Hashtable is legacy synchronized; HashMap is unsynchronized and allows one null key—prefer HashMap with external sync if needed.
Example code
// Hashtable legacy; prefer HashMapQuestion 13
Segmented or node-level locking vs wrapping HashMap with synchronized—better concurrent reads/writes.
Example code
Map<String, Integer> c = new ConcurrentHashMap<>();Question 14
Checked must be declared or caught (IOException). Unchecked extend RuntimeException (NPE)—compiler doesn't force handling.
Example code
try { throw new IOException("x"); } catch (IOException e) { }Question 15
Auto-close AutoCloseable resources; preferred over manual finally for streams and connections.
Example code
try (var in = Files.newInputStream(Path.of("p"))) { }Question 16
Type parameters removed at runtime; casts inserted—can't new T() or instanceof List<String>.
Example code
List<String> list = new ArrayList<>(); // type erasure at runtimeQuestion 17
PECS: producer extends, consumer super—flexible APIs for read vs write.
Example code
List<? extends Number> nums; List<? super Integer> cons;Question 18
Intrinsic lock on object or class; mutual exclusion and visibility guarantees with memory model.
Example code
synchronized (lock) { /* critical */ }Question 19
Reads/writes go through main memory for visibility; not atomic for compound actions like increment.
Example code
volatile boolean flag; // visibility, not atomicity for flag++Question 20
Thread is a thread; Runnable is task code—prefer implementing Runnable/Callable for composition.
Example code
new Thread(() -> System.out.println("run")).start();Question 21
Thread pool abstraction; submit Callables/Futures; shutdown gracefully to avoid leaks.
Example code
ExecutorService ex = Executors.newFixedThreadPool(4); ex.submit(() -> 1); ex.shutdown();Question 22
Stack: frames, locals, references. Heap: objects; GC manages unreachable objects.
Example code
// stack frames, heap objectsQuestion 23
Generational hypothesis; young/old collections; tuning depends on latency vs throughput (G1, ZGC, etc.).
Example code
System.gc(); // hint onlyQuestion 24
Belongs to class not instance; static fields shared; static methods no this.
Example code
class S { static int x; static void m() {} }Question 25
Variable assign-once; method not overrideable; class not extendable—design and optimization hints.
Example code
final class C {} // cannot extendQuestion 26
private, package (default), protected, public—top-level classes only public or package.
Example code
public void m() {} // package/private/protectedQuestion 27
Equal objects must have same hashCode; changing fields used in equality breaks collections.
Example code
@Override public boolean equals(Object o) { return super.equals(o); }Question 28
Comparable natural ordering on class; Comparator external strategy for sort/Trees.
Example code
list.sort(Comparator.naturalOrder());Question 29
Explicit absence of value vs null; avoid Optional fields/parameters—mainly return types.
Example code
Optional.ofNullable(s).orElse("");Question 30
Functional-style pipelines on collections: map/filter/reduce; lazy intermediate ops, terminal triggers execution.
Example code
list.stream().map(String::toUpperCase).toList();Question 31
Syntax sugar for lambdas calling existing methods: Class::static, instance::method, Class::instance.
Example code
Function<String, Integer> f = String::length;Question 32
Immutable data carriers with generated equals/hashCode/toString—replace verbose POJOs.
Example code
record Point(int x, int y) {}Question 33
Restrict which classes extend/implement—exhaustive switches with pattern matching.
Example code
sealed interface I permits A, B {}Question 34
if (o instanceof String s) { use s }—binds casted variable.
Example code
if (o instanceof String s) { System.out.println(s); }Question 35
Lightweight threads mapped to carrier threads—simplify scalable blocking I/O code.
Example code
Thread.startVirtualThread(() -> System.out.println("vt"));Question 36
Foundation for virtual threads and structured concurrency APIs.
Example code
// Project Loom: virtual threadsQuestion 37
module-info.java declares exports/requires—strong encapsulation beyond classpath jars.
Example code
// module-info.java exports com.app.api;Question 38
Convention-over-configuration; embedded server; starters wire dependencies; production-ready actuator endpoints.
Example code
@SpringBootApplication public class App { public static void main(String[] a) { SpringApplication.run(App.class, a); } }Question 39
Dependency injection by type/qualifier; prefer constructor injection for immutability and testing.
Example code
@Autowired // prefer constructor injectionQuestion 40
javax/jakarta validation annotations on DTOs; fail fast on bad input in APIs.
Example code
@NotNull String name; // jakarta.validationQuestion 41
ORM maps entities to tables; know lazy loading, N+1 queries, and session flush boundaries.
Example code
@Entity class User { @Id Long id; }Question 42
Standard ORM API; Hibernate is common implementation—EntityManager, persistence context.
Example code
entityManager.persist(user);Question 43
JPQL is object-oriented query language; native for DB-specific tuning when needed.
Example code
em.createQuery("SELECT u FROM User u", User.class);Question 44
HikariCP default in Spring Boot—reuse DB connections, tune pool size vs DB limits.
Example code
// spring.datasource.hikari.maximum-pool-size=10Question 45
@Transactional AOP proxy; self-invocation bypasses proxy—common pitfall.
Example code
@Transactional public void save() {}Question 46
DispatcherServlet, handler mapping, controller, view resolver—know where filters intercept.
Example code
@GetMapping("/x") String x() { return "v"; }Question 47
Stateless HTTP resources, proper verbs/status codes, idempotent PUT/DELETE expectations.
Example code
@GetMapping("/users/{id}") User get(@PathVariable long id) { return repo.findById(id); }Question 48
Filter chain, authentication vs authorization, CSRF for sessions, JWT resource server patterns.
Example code
http.authorizeHttpRequests(a -> a.anyRequest().authenticated());Question 49
Signed claims; verify signature and exp; don't put secrets in payload; mind revocation story.
Example code
Jwts.parser().verifyWith(key).build().parseSignedClaims(token);Question 50
Delegated authorization; know roles of resource owner, client, authorization server, resource server.
Example code
// spring-security-oauth2-resource-serverQuestion 51
Log-based messaging; partitions, consumer groups, at-least-once vs exactly-once tradeoffs.
Example code
@KafkaListener(topics = "orders") void listen(String m) {}Question 52
@Test, parameterized tests, extensions—modern default over JUnit 4.
Example code
@Test void t() { assertEquals(2, 1 + 1); }Question 53
Mock collaborators; verify interactions; avoid over-mocking domain logic.
Example code
when(repo.findById(1L)).thenReturn(Optional.of(u));Question 54
Spin real DB/brokers in Docker for integration tests—slower but high fidelity.
Example code
@Container static PostgreSQLContainer<?> pg = new PostgreSQLContainer<>("postgres:16");Question 55
pom.xml lifecycle phases; dependency scope compile/test/provided; reactor multi-module builds.
Example code
// mvn -q testQuestion 56
Kotlin DSL, incremental builds, task graph—faster for large projects when tuned.
Example code
// ./gradlew testQuestion 57
Logging facade; bind Logback/Log4j2 underneath—use parameterized messages, not string concat.
Example code
log.info("user={}", id);Question 58
Metrics facade in Spring Boot; Prometheus/OTel export for observability.
Example code
Counter.builder("api.calls").register(registry).increment();Question 59
Traces/metrics/logs correlation across services—vendor-neutral instrumentation.
Example code
Span span = tracer.spanBuilder("op").startSpan();Question 60
-Xmx/-Xms, GC logs, pause targets—profile before guessing flags.
Example code
// -Xmx512m -XX:+UseG1GCQuestion 61
Call native code from Java—breaks portability; careful with memory and exceptions across boundary.
Example code
// native void n();Question 62
Low-level memory; mostly off-limits—know it exists for frameworks, not app code.
Example code
// sun.misc.Unsafe — avoidQuestion 63
Understanding stack machine helps read javap and debug verifier errors.
Example code
// javap -c MyClassQuestion 64
Delegation model; issues with duplicate jars; modular system changes visibility rules.
Example code
// ServiceLoader.load(Driver.class)Question 65
ServiceLoader discovers implementations—used by JDBC drivers and logging bridges.
Example code
ServiceLoader.load(MyService.class).findFirst();Question 66
java.util.concurrent locks vs synchronized—tryLock avoids indefinite blocking.
Example code
if (lock.tryLock()) try {} finally { lock.unlock(); }Question 67
One-shot barrier; CyclicBarrier reusable; choose per coordination pattern.
Example code
CountDownLatch l = new CountDownLatch(1); l.countDown(); l.await();Question 68
Composable async pipelines; handle thread pool for async supply/run carefully.
Example code
CompletableFuture.supplyAsync(() -> 1).thenApply(x -> x + 1).join();Question 69
Publisher/Subscriber backpressure; Project Reactor in Spring WebFlux—mind debugging complexity.
Example code
Flux.just(1, 2).map(x -> x * 2).subscribe(System.out::println);Question 70
Non-blocking stack on Netty—use when scalability of I/O bound workloads warrants reactive style.
Example code
@GetMapping("/flux") Flux<Integer> f() { return Flux.range(1, 3); }Question 71
Blocking request-per-thread model; still dominant in Spring MVC on Tomcat.
Example code
protected void doGet(HttpServletRequest req, HttpServletResponse res) {}Question 72
Connector threads vs worker threads; tune acceptCount and maxThreads under load.
Example code
// server.tomcat.threads.max in Spring BootQuestion 73
Event-loop async I/O underpinning many servers—understand when WebFlux uses it.
Example code
// Netty event loop for WebFluxQuestion 74
Protobuf over HTTP/2; strong contracts; streaming RPCs—interop across languages.
Example code
// ManagedChannel + stub RPCQuestion 75
Compact binary schema evolution with field numbers—backward compatible wire format.
Example code
UserProto.User.parseFrom(bytes);Question 76
JSON binding; avoid default typing for security; configure unknown property handling.
Example code
ObjectMapper m = new ObjectMapper();
User u = m.readValue(json, User.class);Question 77
Validate different subsets for create vs update flows.
Example code
@Validated(OnCreate.class)Question 78
Compile-time bean mappers—faster and safer than reflection mappers for DTOs.
Example code
@Mapper interface U { Target to(Source s); }Question 79
Annotations reduce boilerplate; know what bytecode it generates and IDE/plugin needs.
Example code
@Data class D { private int x; }Question 80
final fields, defensive copies for getters when exposing mutable internals.
Example code
public final class I { private final int x; }Question 81
Return copies of internal arrays/collections to preserve invariants.
Example code
public List<T> items() { return List.copyOf(internal); }Question 82
ConcurrentModificationException on structural change while iterating—use concurrent collections if needed.
Example code
for (var x : list) { list.remove(x); } // ConcurrentModificationExceptionQuestion 83
Snapshot iterator, writes copy array—good for frequent reads, rare writes.
Example code
new CopyOnWriteArrayList<>(List.of(1, 2));Question 84
Producer-consumer backbone; LinkedBlockingQueue vs ArrayBlockingQueue tradeoffs.
Example code
ArrayBlockingQueue<Integer> q = new ArrayBlockingQueue<>(10); q.put(1);Question 85
Work-stealing for divide-and-conquer CPU tasks—common pool used by parallel streams.
Example code
ForkJoinPool.commonPool().submit(() -> 1).get();Question 86
Uses common pool; may contend and hurt latency for small tasks or blocking work.
Example code
list.parallelStream().map(...); // may contendQuestion 87
Deprecated for removal—modern Java moves to capability-style and external policy tools.
Example code
// deprecated / being removedQuestion 88
Java serialization pitfalls—use JSON/Protobuf for services; SerialUID for compatibility.
Example code
ObjectOutputStream oos = new ObjectOutputStream(out); oos.writeObject(obj);Question 89
Liskov issues—prefer composition or canEqual pattern in deep hierarchies.
Example code
// prefer composition over deep equals in hierarchiesQuestion 90
Singleton pattern built-in; switch exhaustive; can hold methods and implement interfaces.
Example code
enum Color { RED, GREEN }Question 91
Expression form with yield; cleaner than break chains in Java 14+.
Example code
int x = switch (c) { case A -> 1; default -> 0; };Question 92
Multiline string literals (Java 15+) for SQL/HTML snippets with indentation control.
Example code
String sql = """
SELECT * FROM t
""";Question 93
Compact constructors validate; consider migration from legacy beans.
Example code
record R(int x) {} // JSON mappingQuestion 94
Exhaustive pattern matching in switches—compiler checks coverage.
Example code
sealed interface S permits A {}Question 95
Project Panama foreign memory/API—replace JNI for safer native interop over time.
Example code
// MemorySegment.allocateNative(16)Question 96
SIMD API incubating/preview—numeric performance on supporting CPUs.
Example code
// Vector API SIMDQuestion 97
Kubernetes-native Java; build-time DI and GraalVM native image options for fast startup.
Example code
// @Path("/hello") @GET String hi() { return "hi"; }Question 98
Compile-time AOT DI and low reflection—good for serverless and microservices cold start.
Example code
@Controller("/x") class C { @Get String g() { return "ok"; } }Question 99
Native image ahead-of-time compilation—smaller footprint and faster cold starts vs JIT tradeoffs.
Example code
// native-image -jar app.jarQuestion 100
Low-overhead profiling and diagnostics built into the JVM for production insights.
Example code
// jcmd <pid> JFR.startQuestion 101
Analyze JFR recordings for hotspots, allocations, and latency issues.
Example code
// analyze .jfr recordingsQuestion 102
Synchronized blocks or native code can pin virtual threads—avoid blocking on carriers unintentionally.
Example code
synchronized (lock) { /* may pin VT */ }