Interview Q&A

Pick a topic — languages & databases — 100+ questions and answers in the center column.

Java

Interview questions & answers

JVM, OOP, collections, concurrency, memory.

102 questions

  1. Question 1

    What are JVM, JRE, and JDK?

    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"); } }
  2. Question 2

    Why is Java platform-independent?

    Source compiles to bytecode; JVMs for each OS execute it with JIT compilation.

    Example code

    // javac Main.java && java Main
  3. Question 3

    What does public static void main mean?

    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); }
  4. Question 4

    Four pillars of OOP?

    Encapsulation, abstraction, inheritance, polymorphism—know a Java example for each.

    Example code

    // encapsulation: private fields + getters
  5. Question 5

    Class vs object?

    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; } }
  6. Question 6

    Interface vs abstract class?

    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(); }
  7. Question 7

    == vs equals()?

    == 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"));
  8. Question 8

    String immutability?

    Strings can't change; operations return new instances—safe for sharing and string pool.

    Example code

    String s = "hi"; // immutable
  9. Question 9

    StringBuilder vs StringBuffer?

    Both mutable char sequences; StringBuffer is synchronized, StringBuilder faster single-threaded.

    Example code

    StringBuilder sb = new StringBuilder(); sb.append("x");
  10. Question 10

    ArrayList vs LinkedList?

    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);
  11. Question 11

    HashMap internals?

    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);
  12. Question 12

    HashMap vs Hashtable?

    Hashtable is legacy synchronized; HashMap is unsynchronized and allows one null key—prefer HashMap with external sync if needed.

    Example code

    // Hashtable legacy; prefer HashMap
  13. Question 13

    ConcurrentHashMap?

    Segmented or node-level locking vs wrapping HashMap with synchronized—better concurrent reads/writes.

    Example code

    Map<String, Integer> c = new ConcurrentHashMap<>();
  14. Question 14

    Checked vs unchecked exceptions?

    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) { }
  15. Question 15

    try-with-resources?

    Auto-close AutoCloseable resources; preferred over manual finally for streams and connections.

    Example code

    try (var in = Files.newInputStream(Path.of("p"))) { }
  16. Question 16

    Generics type erasure?

    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 runtime
  17. Question 17

    Wildcards ? extends / super?

    PECS: producer extends, consumer super—flexible APIs for read vs write.

    Example code

    List<? extends Number> nums; List<? super Integer> cons;
  18. Question 18

    synchronized keyword?

    Intrinsic lock on object or class; mutual exclusion and visibility guarantees with memory model.

    Example code

    synchronized (lock) { /* critical */ }
  19. Question 19

    volatile?

    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++
  20. Question 20

    Thread vs Runnable?

    Thread is a thread; Runnable is task code—prefer implementing Runnable/Callable for composition.

    Example code

    new Thread(() -> System.out.println("run")).start();
  21. Question 21

    ExecutorService?

    Thread pool abstraction; submit Callables/Futures; shutdown gracefully to avoid leaks.

    Example code

    ExecutorService ex = Executors.newFixedThreadPool(4); ex.submit(() -> 1); ex.shutdown();
  22. Question 22

    Stack vs heap?

    Stack: frames, locals, references. Heap: objects; GC manages unreachable objects.

    Example code

    // stack frames, heap objects
  23. Question 23

    Garbage collection basics?

    Generational hypothesis; young/old collections; tuning depends on latency vs throughput (G1, ZGC, etc.).

    Example code

    System.gc(); // hint only
  24. Question 24

    What does static mean?

    Belongs to class not instance; static fields shared; static methods no this.

    Example code

    class S { static int x; static void m() {} }
  25. Question 25

    final variable/method/class?

    Variable assign-once; method not overrideable; class not extendable—design and optimization hints.

    Example code

    final class C {} // cannot extend
  26. Question 26

    Access modifiers?

    private, package (default), protected, public—top-level classes only public or package.

    Example code

    public void m() {} // package/private/protected
  27. Question 27

    equals and hashCode contract?

    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); }
  28. Question 28

    Comparable vs Comparator?

    Comparable natural ordering on class; Comparator external strategy for sort/Trees.

    Example code

    list.sort(Comparator.naturalOrder());
  29. Question 29

    Optional purpose?

    Explicit absence of value vs null; avoid Optional fields/parameters—mainly return types.

    Example code

    Optional.ofNullable(s).orElse("");
  30. Question 30

    Streams API?

    Functional-style pipelines on collections: map/filter/reduce; lazy intermediate ops, terminal triggers execution.

    Example code

    list.stream().map(String::toUpperCase).toList();
  31. Question 31

    Method references?

    Syntax sugar for lambdas calling existing methods: Class::static, instance::method, Class::instance.

    Example code

    Function<String, Integer> f = String::length;
  32. Question 32

    Records (Java 16+)?

    Immutable data carriers with generated equals/hashCode/toString—replace verbose POJOs.

    Example code

    record Point(int x, int y) {}
  33. Question 33

    Sealed classes?

    Restrict which classes extend/implement—exhaustive switches with pattern matching.

    Example code

    sealed interface I permits A, B {}
  34. Question 34

    Pattern matching instanceof?

    if (o instanceof String s) { use s }—binds casted variable.

    Example code

    if (o instanceof String s) { System.out.println(s); }
  35. Question 35

    Virtual threads (Java 21)?

    Lightweight threads mapped to carrier threads—simplify scalable blocking I/O code.

    Example code

    Thread.startVirtualThread(() -> System.out.println("vt"));
  36. Question 36

    Project Loom relevance?

    Foundation for virtual threads and structured concurrency APIs.

    Example code

    // Project Loom: virtual threads
  37. Question 37

    Modules (JPMS)?

    module-info.java declares exports/requires—strong encapsulation beyond classpath jars.

    Example code

    // module-info.java exports com.app.api;
  38. Question 38

    Spring Boot basics?

    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); } }
  39. Question 39

    Spring @Autowired?

    Dependency injection by type/qualifier; prefer constructor injection for immutability and testing.

    Example code

    @Autowired // prefer constructor injection
  40. Question 40

    What is Bean validation (Java)?

    javax/jakarta validation annotations on DTOs; fail fast on bad input in APIs.

    Example code

    @NotNull String name; // jakarta.validation
  41. Question 41

    What is Hibernate (Java)?

    ORM maps entities to tables; know lazy loading, N+1 queries, and session flush boundaries.

    Example code

    @Entity class User { @Id Long id; }
  42. Question 42

    What is JPA (Java)?

    Standard ORM API; Hibernate is common implementation—EntityManager, persistence context.

    Example code

    entityManager.persist(user);
  43. Question 43

    What is JPQL vs native SQL (Java)?

    JPQL is object-oriented query language; native for DB-specific tuning when needed.

    Example code

    em.createQuery("SELECT u FROM User u", User.class);
  44. Question 44

    What is Connection pooling (Java)?

    HikariCP default in Spring Boot—reuse DB connections, tune pool size vs DB limits.

    Example code

    // spring.datasource.hikari.maximum-pool-size=10
  45. Question 45

    What is Transactions (Java)?

    @Transactional AOP proxy; self-invocation bypasses proxy—common pitfall.

    Example code

    @Transactional public void save() {}
  46. Question 46

    What is Spring MVC flow (Java)?

    DispatcherServlet, handler mapping, controller, view resolver—know where filters intercept.

    Example code

    @GetMapping("/x") String x() { return "v"; }
  47. Question 47

    What is REST principles (Java)?

    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); }
  48. Question 48

    What is Spring Security (Java)?

    Filter chain, authentication vs authorization, CSRF for sessions, JWT resource server patterns.

    Example code

    http.authorizeHttpRequests(a -> a.anyRequest().authenticated());
  49. Question 49

    What is JWT (Java)?

    Signed claims; verify signature and exp; don't put secrets in payload; mind revocation story.

    Example code

    Jwts.parser().verifyWith(key).build().parseSignedClaims(token);
  50. Question 50

    What is OAuth2 (Java)?

    Delegated authorization; know roles of resource owner, client, authorization server, resource server.

    Example code

    // spring-security-oauth2-resource-server
  51. Question 51

    What is Kafka (Java)?

    Log-based messaging; partitions, consumer groups, at-least-once vs exactly-once tradeoffs.

    Example code

    @KafkaListener(topics = "orders") void listen(String m) {}
  52. Question 52

    What is JUnit 5 (Java)?

    @Test, parameterized tests, extensions—modern default over JUnit 4.

    Example code

    @Test void t() { assertEquals(2, 1 + 1); }
  53. Question 53

    What is Mockito (Java)?

    Mock collaborators; verify interactions; avoid over-mocking domain logic.

    Example code

    when(repo.findById(1L)).thenReturn(Optional.of(u));
  54. Question 54

    What is Testcontainers (Java)?

    Spin real DB/brokers in Docker for integration tests—slower but high fidelity.

    Example code

    @Container static PostgreSQLContainer<?> pg = new PostgreSQLContainer<>("postgres:16");
  55. Question 55

    What is Maven (Java)?

    pom.xml lifecycle phases; dependency scope compile/test/provided; reactor multi-module builds.

    Example code

    // mvn -q test
  56. Question 56

    What is Gradle (Java)?

    Kotlin DSL, incremental builds, task graph—faster for large projects when tuned.

    Example code

    // ./gradlew test
  57. Question 57

    What is SLF4J (Java)?

    Logging facade; bind Logback/Log4j2 underneath—use parameterized messages, not string concat.

    Example code

    log.info("user={}", id);
  58. Question 58

    What is Micrometer (Java)?

    Metrics facade in Spring Boot; Prometheus/OTel export for observability.

    Example code

    Counter.builder("api.calls").register(registry).increment();
  59. Question 59

    What is OpenTelemetry (Java)?

    Traces/metrics/logs correlation across services—vendor-neutral instrumentation.

    Example code

    Span span = tracer.spanBuilder("op").startSpan();
  60. Question 60

    What is Virtual machine tuning (Java)?

    -Xmx/-Xms, GC logs, pause targets—profile before guessing flags.

    Example code

    // -Xmx512m -XX:+UseG1GC
  61. Question 61

    What is JNI (Java)?

    Call native code from Java—breaks portability; careful with memory and exceptions across boundary.

    Example code

    // native void n();
  62. Question 62

    What is Unsafe (internal) (Java)?

    Low-level memory; mostly off-limits—know it exists for frameworks, not app code.

    Example code

    // sun.misc.Unsafe — avoid
  63. Question 63

    What is Bytecode (Java)?

    Understanding stack machine helps read javap and debug verifier errors.

    Example code

    // javap -c MyClass
  64. Question 64

    What is Classloader (Java)?

    Delegation model; issues with duplicate jars; modular system changes visibility rules.

    Example code

    // ServiceLoader.load(Driver.class)
  65. Question 65

    What is SPI pattern (Java)?

    ServiceLoader discovers implementations—used by JDBC drivers and logging bridges.

    Example code

    ServiceLoader.load(MyService.class).findFirst();
  66. Question 66

    What is tryLock and locks (Java)?

    java.util.concurrent locks vs synchronized—tryLock avoids indefinite blocking.

    Example code

    if (lock.tryLock()) try {} finally { lock.unlock(); }
  67. Question 67

    What is CountDownLatch (Java)?

    One-shot barrier; CyclicBarrier reusable; choose per coordination pattern.

    Example code

    CountDownLatch l = new CountDownLatch(1); l.countDown(); l.await();
  68. Question 68

    What is CompletableFuture (Java)?

    Composable async pipelines; handle thread pool for async supply/run carefully.

    Example code

    CompletableFuture.supplyAsync(() -> 1).thenApply(x -> x + 1).join();
  69. Question 69

    What is Reactive streams (Java)?

    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);
  70. Question 70

    What is WebFlux (Java)?

    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); }
  71. Question 71

    What is Servlet (Java)?

    Blocking request-per-thread model; still dominant in Spring MVC on Tomcat.

    Example code

    protected void doGet(HttpServletRequest req, HttpServletResponse res) {}
  72. Question 72

    What is Tomcat (Java)?

    Connector threads vs worker threads; tune acceptCount and maxThreads under load.

    Example code

    // server.tomcat.threads.max in Spring Boot
  73. Question 73

    What is Netty (Java)?

    Event-loop async I/O underpinning many servers—understand when WebFlux uses it.

    Example code

    // Netty event loop for WebFlux
  74. Question 74

    What is gRPC (Java)?

    Protobuf over HTTP/2; strong contracts; streaming RPCs—interop across languages.

    Example code

    // ManagedChannel + stub RPC
  75. Question 75

    What is Protobuf (Java)?

    Compact binary schema evolution with field numbers—backward compatible wire format.

    Example code

    UserProto.User.parseFrom(bytes);
  76. Question 76

    What is Jackson (Java)?

    JSON binding; avoid default typing for security; configure unknown property handling.

    Example code

    ObjectMapper m = new ObjectMapper();
    User u = m.readValue(json, User.class);
  77. Question 77

    What is Bean validation groups (Java)?

    Validate different subsets for create vs update flows.

    Example code

    @Validated(OnCreate.class)
  78. Question 78

    What is MapStruct (Java)?

    Compile-time bean mappers—faster and safer than reflection mappers for DTOs.

    Example code

    @Mapper interface U { Target to(Source s); }
  79. Question 79

    What is Lombok (Java)?

    Annotations reduce boilerplate; know what bytecode it generates and IDE/plugin needs.

    Example code

    @Data class D { private int x; }
  80. Question 80

    What is Immutability (Java)?

    final fields, defensive copies for getters when exposing mutable internals.

    Example code

    public final class I { private final int x; }
  81. Question 81

    What is Defensive copying (Java)?

    Return copies of internal arrays/collections to preserve invariants.

    Example code

    public List<T> items() { return List.copyOf(internal); }
  82. Question 82

    What is Fail-fast iterators (Java)?

    ConcurrentModificationException on structural change while iterating—use concurrent collections if needed.

    Example code

    for (var x : list) { list.remove(x); } // ConcurrentModificationException
  83. Question 83

    What is CopyOnWriteArrayList (Java)?

    Snapshot iterator, writes copy array—good for frequent reads, rare writes.

    Example code

    new CopyOnWriteArrayList<>(List.of(1, 2));
  84. Question 84

    What is BlockingQueue (Java)?

    Producer-consumer backbone; LinkedBlockingQueue vs ArrayBlockingQueue tradeoffs.

    Example code

    ArrayBlockingQueue<Integer> q = new ArrayBlockingQueue<>(10); q.put(1);
  85. Question 85

    What is ForkJoinPool (Java)?

    Work-stealing for divide-and-conquer CPU tasks—common pool used by parallel streams.

    Example code

    ForkJoinPool.commonPool().submit(() -> 1).get();
  86. Question 86

    What is parallelStream caution (Java)?

    Uses common pool; may contend and hurt latency for small tasks or blocking work.

    Example code

    list.parallelStream().map(...); // may contend
  87. Question 87

    What is SecurityManager (Java)?

    Deprecated for removal—modern Java moves to capability-style and external policy tools.

    Example code

    // deprecated / being removed
  88. Question 88

    What is Serialization (Java)?

    Java serialization pitfalls—use JSON/Protobuf for services; SerialUID for compatibility.

    Example code

    ObjectOutputStream oos = new ObjectOutputStream(out); oos.writeObject(obj);
  89. Question 89

    What is equals symmetry with inheritance (Java)?

    Liskov issues—prefer composition or canEqual pattern in deep hierarchies.

    Example code

    // prefer composition over deep equals in hierarchies
  90. Question 90

    What is Enum (Java)?

    Singleton pattern built-in; switch exhaustive; can hold methods and implement interfaces.

    Example code

    enum Color { RED, GREEN }
  91. Question 91

    What is Switch expressions (Java)?

    Expression form with yield; cleaner than break chains in Java 14+.

    Example code

    int x = switch (c) { case A -> 1; default -> 0; };
  92. Question 92

    What is Text blocks (Java)?

    Multiline string literals (Java 15+) for SQL/HTML snippets with indentation control.

    Example code

    String sql = """
      SELECT * FROM t
      """;
  93. Question 93

    What is Records serialization (Java)?

    Compact constructors validate; consider migration from legacy beans.

    Example code

    record R(int x) {} // JSON mapping
  94. Question 94

    What is Sealed interfaces (Java)?

    Exhaustive pattern matching in switches—compiler checks coverage.

    Example code

    sealed interface S permits A {}
  95. Question 95

    What is Foreign (Java)?

    Project Panama foreign memory/API—replace JNI for safer native interop over time.

    Example code

    // MemorySegment.allocateNative(16)
  96. Question 96

    What is Vector (Java)?

    SIMD API incubating/preview—numeric performance on supporting CPUs.

    Example code

    // Vector API SIMD
  97. Question 97

    What is Quarkus (Java)?

    Kubernetes-native Java; build-time DI and GraalVM native image options for fast startup.

    Example code

    // @Path("/hello") @GET String hi() { return "hi"; }
  98. Question 98

    What is Micronaut (Java)?

    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"; } }
  99. Question 99

    What is GraalVM (Java)?

    Native image ahead-of-time compilation—smaller footprint and faster cold starts vs JIT tradeoffs.

    Example code

    // native-image -jar app.jar
  100. Question 100

    What is JFR (Java Flight Recorder) (Java)?

    Low-overhead profiling and diagnostics built into the JVM for production insights.

    Example code

    // jcmd <pid> JFR.start
  101. Question 101

    What is JMC (Mission Control) (Java)?

    Analyze JFR recordings for hotspots, allocations, and latency issues.

    Example code

    // analyze .jfr recordings
  102. Question 102

    What is Virtual thread pinning (Java)?

    Synchronized blocks or native code can pin virtual threads—avoid blocking on carriers unintentionally.

    Example code

    synchronized (lock) { /* may pin VT */ }