Chaturmind
LearnDSASystem DesignInterview PrepDevOpsEngineering GrowthBlog
Start learning
Chaturmind

Structured learning paths for engineers who want to go deep. Written by practitioners.

Learn

  • Java
  • DSA
  • System Design
  • Spring Boot
  • AI / ML
  • DevOps
  • Engineering Growth
  • Java Interview Prep

Company

  • Blog
  • Contact

Legal

  • Privacy Policy
  • Terms of Service

© 2026 Chaturmind. All rights reserved.

Built for engineers who want to go deep.


← Java Interview Prep: 5–8 Years

Revise the 2–5 Years Tier

  • Revise: Core Java & Java 8+ (2–5 Years Tier)
  • Revise: Multithreading & Concurrency (2–5 Years Tier)
  • Revise: Spring Framework, Spring Boot & Security (2–5 Years Tier)
  • Revise: Kafka, Git/Maven/Gradle, Deployment & Testing (2–5 Years Tier)

Advanced Core Java

  • Advanced OOP & Design Scenarios — Interview Questions
  • Advanced Concurrency, Collections & Memory — Interview Questions
  • Modern Java Language Features & Annotations — Interview Questions
  • Class Loading, Reflection, Serialization & Idioms — Interview Questions

Java Design Patterns in Depth

  • Design Patterns Overview & Singleton — Interview Questions
  • Factory & Abstract Factory Patterns — Interview Questions
  • Builder & Prototype Patterns — Interview Questions
  • Adapter & Bridge Patterns — Interview Questions
  • Composite & Decorator Patterns — Interview Questions
  • Facade & Proxy Patterns — Interview Questions
  • Chain of Responsibility & Observer Patterns — Interview Questions
  • Strategy & Template Method Patterns — Interview Questions
  • Command Pattern — Interview Questions

Advanced Spring Boot

  • Logging, Configuration & Actuator (Advanced) — Interview Questions
  • Transactions, Multiple Datasources & Query Tuning — Interview Questions
  • Validation & REST API Design (Advanced) — Interview Questions
  • Reactive, Async & Scheduling in Spring Boot — Interview Questions
  • Deployment, High Availability, Scaling & Caching — Interview Questions
  • Custom Starters, DI, Testing & DevTools — Interview Questions

Spring Security for APIs

  • Securing REST APIs End to End — Interview Questions

Microservices at Scale

  • Monolith Migration, Communication & Spring Cloud — Interview Questions
  • Data Consistency, Sagas & Kafka Messaging — Interview Questions
  • Tracing, Discovery, Load Balancing, Service Mesh & Resilience — Interview Questions
  • Deployment, Scaling & Security for Microservices — Interview Questions

Microservice Design Patterns

  • API Gateway, Circuit Breaker & Retry Patterns — Interview Questions
  • Service Discovery & Database per Service Patterns — Interview Questions
  • Saga, Choreography & Orchestration Patterns — Interview Questions
  • Bulkhead & Strangler Fig Patterns — Interview Questions
Chaturmind
← Java Interview Prep: 5–8 Years

Revise the 2–5 Years Tier

  • Revise: Core Java & Java 8+ (2–5 Years Tier)
  • Revise: Multithreading & Concurrency (2–5 Years Tier)
  • Revise: Spring Framework, Spring Boot & Security (2–5 Years Tier)
  • Revise: Kafka, Git/Maven/Gradle, Deployment & Testing (2–5 Years Tier)

Advanced Core Java

  • Advanced OOP & Design Scenarios — Interview Questions
  • Advanced Concurrency, Collections & Memory — Interview Questions
  • Modern Java Language Features & Annotations — Interview Questions
  • Class Loading, Reflection, Serialization & Idioms — Interview Questions

Java Design Patterns in Depth

  • Design Patterns Overview & Singleton — Interview Questions
  • Factory & Abstract Factory Patterns — Interview Questions
  • Builder & Prototype Patterns — Interview Questions
  • Adapter & Bridge Patterns — Interview Questions
  • Composite & Decorator Patterns — Interview Questions
  • Facade & Proxy Patterns — Interview Questions
  • Chain of Responsibility & Observer Patterns — Interview Questions
  • Strategy & Template Method Patterns — Interview Questions
  • Command Pattern — Interview Questions

Advanced Spring Boot

  • Logging, Configuration & Actuator (Advanced) — Interview Questions
  • Transactions, Multiple Datasources & Query Tuning — Interview Questions
  • Validation & REST API Design (Advanced) — Interview Questions
  • Reactive, Async & Scheduling in Spring Boot — Interview Questions
  • Deployment, High Availability, Scaling & Caching — Interview Questions
  • Custom Starters, DI, Testing & DevTools — Interview Questions

Spring Security for APIs

  • Securing REST APIs End to End — Interview Questions

Microservices at Scale

  • Monolith Migration, Communication & Spring Cloud — Interview Questions
  • Data Consistency, Sagas & Kafka Messaging — Interview Questions
  • Tracing, Discovery, Load Balancing, Service Mesh & Resilience — Interview Questions
  • Deployment, Scaling & Security for Microservices — Interview Questions

Microservice Design Patterns

  • API Gateway, Circuit Breaker & Retry Patterns — Interview Questions
  • Service Discovery & Database per Service Patterns — Interview Questions
  • Saga, Choreography & Orchestration Patterns — Interview Questions
  • Bulkhead & Strangler Fig Patterns — Interview Questions
HomeLearnJava Interview PrepJava Interview Prep: 5–8 YearsRevise the 2–5 Years Tier
✓ FreeAdvanced· 47 min read

Revise: Core Java & Java 8+ (2–5 Years Tier)

Every 2–5-year Core Java and Java 8+ question — collections internals, immutability, generics, memory, streams, functional interfaces, Optional — as a one-line answer linked to the full answer.

Published September 25, 2026


How to use this revision

This page condenses every question from the 2 to 5 Years course in these areas into a single line: the question, linked to its full answer, and the one-sentence answer you should be able to give instantly. Read down the list and answer each question aloud before reading the line. Wherever you hesitate, follow the link and revise the full answer — interviewers at your level expect these basics to be fluent, and they often open with them before going deeper.

Intermediate Core Java

Intermediate OOP & Language Features — Interview Questions — open the lesson

  • What is the Builder pattern, and how is it different from the Factory pattern? — Builder constructs a complex object step by step through a fluent API, and then produces the finished, usually immutable, object with build().
  • What's the impact of declaring a method final on inheritance? — A final method can't be overridden, so every subclass inherits exactly that implementation. Use it to protect behaviour that invariants or security depend on.
  • Can method overloading be resolved at runtime? — No. Choosing an overload is a compile-time decision, based on the static types of the arguments. At runtime, the JVM only performs dynamic dispatch on the receiver object, to pick an override of the method signature that was already chosen.
  • How does Java resolve a call to an overloaded method? — The compiler: Collects the accessible methods with that name; Keeps the ones applicable to the arguments, in three phases:; Stops at the first phase that finds any match, and picks the most specific method. If no single method is most specific, the call is ambiguous, and it's…
  • How does Java determine which method to call when methods are overloaded? (A common rephrasing) — The same compile-time process: match on the method name and the number, types and order of the arguments' static types, applying the three phases above and then choosing the most specific signature.
  • Explain inner classes in Java. — Java has four kinds of nested class: Static nested class: belongs to the outer class, and has no reference to an outer instance. Use it for builders and helper types; Inner (non-static) class: every instance holds a hidden reference to an outer instance, and can use its…
  • Can inner classes declare static members? — Since Java 16, yes. JEP 395 (which finalised records) relaxed the rule, so inner classes can now declare static fields, methods and nested types.
  • What's the significance of an anonymous inner class? — It lets you implement an interface, or extend a class, inline, for one-off use, with no named class. It's handy for callbacks and small strategies.
  • What is a marker interface? — An interface with no methods, which marks a class as having some capability or permission. Code checks for it with instanceof, or with the type system.
  • When would creating a custom marker interface be useful? — When you want the compiler to enforce that only certain classes can be used somewhere. For example, only Auditable entities may be passed to an audit writer, or only Transmittable objects may be sent outside the network boundary.
  • What happens if two packages have a class with the same name? — Nothing breaks. The fully qualified names differ (java.util.Date and java.sql.Date). In a file that uses both, import one, and refer to the other by its fully qualified name.
  • How can you access a package-private class from another package? — You can't, through normal code. That's the point of package-private access. The proper options: Make it public, if it really is part of the API; Expose its behaviour through a public interface or facade in the same package (the usual design); For tests, put the test in the…
  • Can you modify an object referenced by a final variable? — Yes. final fixes the reference, not the object. You can't reassign the variable, but you can call mutating methods on the object it points to.
  • What is the default access level if no modifier is given? — Package-private: visible only to classes in the same package. It's more restrictive than protected (which adds subclasses in other packages), and less restrictive than private.
  • What problems can arise when overloading and overriding are mixed in one hierarchy? — The overload is chosen at compile time, from the static type, but the override is chosen at runtime, from the object.

Enums, Generics, Pass-by-Value & Imports — Interview Questions — open the lesson

  • What are enums, and why are they useful? — An enum is a type with a fixed, type-safe set of instances. Under the hood it's a final class extending java.lang.Enum, with one public static final instance per constant.
  • Can an enum extend another class? — No. Every enum already implicitly extends java.lang.Enum, and Java classes have only one superclass. Enums can implement interfaces, which is how you share behaviour, or make them pluggable.
  • Can an enum extend another class? (Asked again, often as a trick follow-up) — The answer doesn't change: no, because java.lang.Enum is already its superclass. When interviewers repeat the question, they're usually checking the follow-up: "so how would you share code between enums?" Use a common interface with default methods, or delegate to a helper…
  • How do you iterate over all the values of an enum? — Call the compiler-generated static values() method. It returns a new array of the constants, in declaration order.
  • How do you iterate over enum values? (Same question, second phrasing) — values() with a for-each loop, EnumSet.allOf(...), or a stream over values(). To look a constant up by name, use Enum.valueOf(Type.class, "NAME") or Type.valueOf("NAME").
  • What is the diamond operator? — <> (Java 7) lets the compiler infer the generic type arguments of a constructor call from the context, so you don't repeat them: Map<String, List<Order>> byCustomer = new HashMap<>();.
  • What is generic type inference? — The compiler deduces the type arguments of generic methods and constructors from the arguments and the target type, so you rarely need to write them explicitly.
  • What is type erasure? — Generic type information exists only at compile time. The compiler checks the types, inserts the necessary casts, then erases the type parameters.
  • Why can't you create an array of a generic type? — Arrays are reified and covariant. They know their element type at runtime, and check every store (ArrayStoreException).
  • Is Java pass-by-value or pass-by-reference? — Always pass-by-value. For primitives, the value is copied. For objects, the reference is copied. So a method can mutate the object through its copy of the reference, but can't make the caller's variable point to a different object.
  • How do imports affect compilation and class loading? — Imports are purely a compile-time convenience. They let you use simple names instead of fully qualified ones. They don't appear in the bytecode as instructions, don't load classes, and have no runtime cost.
  • What's the difference between import and import static? — import brings types into scope by simple name. import static brings a class's static members (methods and constants) into scope, so you can call max(a, b) instead of Math.max(a, b).
  • How do static imports affect readability and maintainability? — Used for well-known DSL-style APIs (AssertJ, Mockito, Hamcrest, Collectors.*, TimeUnit), they make code read naturally.
  • Give an example of how classes and objects interact in a real application. — In an e-commerce checkout: A Cart object holds CartItems; CheckoutService (a Spring singleton) turns the cart into an Order, asks a PaymentGateway (interface → RazorpayGateway object) to charge it, saves the order through an OrderRepository, and publishes an…
  • Can this be used in a static method or a static block? — No. this refers to the current instance, and static methods and static initialisers run without one. They belong to the class, and run even when no object exists.

Collections Internals & Scenarios — Interview Questions — open the lesson

  • Describe a scenario where you used a PriorityQueue, and why it beat other queues. — Whenever items must be processed by priority, not arrival order. For example: a job scheduler running the earliest-deadline job first; a notification dispatcher where OTPs jump ahead of marketing emails; keeping the top-K items from a stream.
  • What goes wrong when mutable objects are used as HashMap keys? — The entry is stored in a bucket chosen by the key's hash at insertion time. If you then mutate a field that hashCode() uses, lookups compute a different hash, search the wrong bucket, and can't find the entry.
  • What happens if a key class overrides equals() but not hashCode()? — It breaks the contract that equal objects must have equal hash codes. Two logically equal keys get different identity hashes, land in different buckets, and never get compared with equals.
  • How do HashMap and IdentityHashMap differ in handling keys? — HashMap compares keys with equals()/hashCode(), which is logical equality. IdentityHashMap compares with == and System.identityHashCode, which is reference equality.
  • How does Collections.sort() work internally? — Collections.sort(list) calls list.sort(null). The default List.sort copies the list into an array, sorts it with Arrays.sort(Object[]) → TimSort, and writes the elements back.
  • What happens if you sort a list containing null with Collections.sort()? — With natural ordering, compareTo is called on or with null, which throws a NullPointerException. (A one-element list is returned unchanged without comparing, so List.of(null)-like single-element cases don't throw.) Handle nulls explicitly with a null-safe comparator —…
  • Can you sort custom objects with Collections.sort() without a comparator? — Only if the class implements Comparable<T>, which defines its natural ordering in compareTo. Otherwise, sorting fails at runtime with a ClassCastException ("cannot be cast to class java.lang.Comparable").
  • What's the difference between Collections.sort() and Stream.sorted()? — Compared side by side in the full answer (table) — know each row.
  • How do you choose an ArrayList's initial capacity when the list is cleared and reused over and over? — Size it for the typical peak batch (new ArrayList<>(expectedMax)), to avoid repeated growth copies on the first fill.
  • Scenario: how would you compare two custom objects for content equality? — Override equals() and hashCode() over the fields that define the object's identity or value, following the contract (reflexive, symmetric, transitive, consistent, and false for null).
  • Scenario: you store user sessions in a HashMap. How do you make it thread-safe? — Replace it with a ConcurrentHashMap, which allows many concurrent readers and writers with fine-grained locking, and use its atomic compound methods.
  • How does a TreeSet order custom objects (not wrapper classes)? — A TreeSet is backed by a red-black tree (a TreeMap). It orders elements using either: their natural ordering, which requires implementing Comparable; or; a Comparator passed to the constructor.
  • How does a TreeSet sort objects? (Follow-up: what about duplicates?) — Same mechanism as Q12, with the key follow-up: TreeSet decides uniqueness by comparison, not equals. If your comparator says two different employees compare as 0, for example because they have the same salary, the second one is silently dropped.

JVM, Memory & Class Loading — Interview Questions — open the lesson

  • How are strings represented in memory? — A String object holds a byte[] plus a coder flag. Since Java 9 (compact strings), text that fits in Latin-1 uses one byte per character, and anything else uses UTF-16 (two bytes per character).
  • How do JVM optimisations affect application performance? — The JVM starts out interpreting bytecode, profiles what actually runs, and JIT-compiles the hot methods to optimised native code. The main optimisations: Inlining: removes call overhead, and enables further optimisations; Escape analysis: allocates non-escaping objects on the…
  • How do JVM optimisations affect performance? (Common follow-up: what can defeat them?) — The same mechanisms as Q2. The follow-up is what makes them fail: Megamorphic call sites (many implementations at one call site) prevent inlining; Huge methods exceed the inlining limits; Frequently thrown exceptions and heavy reflection slow down hot paths; Excessive…
  • What is a class loader, and how does class loading work? — A class loader finds a class's bytes and turns them into a Class object. Loading is lazy: a class loads when it's first actively used. There are three built-in loaders, arranged in a parent-delegation hierarchy: Bootstrap: core java.base classes. It's native, and appears…
  • Can you unload a class? — Not directly. A class is unloaded only when its defining class loader becomes unreachable, and so do all its classes, their instances and their Class objects.
  • Is it possible to unload a class? (Follow-up: how would you verify it happens?) — Yes, but only through class-loader unloading, as in Q5. To verify it: Log class unloading with -Xlog:class+unload; Watch Metaspace usage in JFR, or jcmd <pid> VM.metaspace; Take a heap dump, and look for multiple instances of your web app's class loader (Eclipse MAT's…
  • How does class loading affect memory usage? — Each loaded class consumes Metaspace (native memory) for its metadata, bytecode, constant pool and JIT data. Its Class object and static fields live on the heap.
  • How does class loading affect memory? (Repeated question: answer from the operations angle) — In production, the symptoms are OutOfMemoryError: Metaspace, or a pod killed for exceeding its memory limit while the heap looks fine. The causes: too many generated classes (for example, unbounded dynamic proxies or scripting engines), or class-loader leaks on redeploy.…
  • How does Java deal with memory leaks? — The garbage collector frees unreachable objects automatically. But a Java "memory leak" is objects that are still reachable but no longer needed, and no GC can fix that. Typical causes: Static or long-lived collections that only grow; Caches without eviction; Listeners that…
  • What tools and techniques help identify and fix memory leaks? — Confirm the pattern. GC logs or metrics show the old generation's floor rising after every full GC; Capture a heap dump with jcmd <pid> GC.heap_dump file.hprof, or automatically with -XX:+HeapDumpOnOutOfMemoryError; Analyse it in Eclipse MAT: the Leak Suspects report,…
  • Describe the Java Memory Model. — The JMM defines what values a read is allowed to see when several threads share variables. It allows compilers and CPUs to reorder and cache operations for speed, except across happens-before edges: program order within a thread; unlocking a monitor → a later lock of the same…
  • What is the visibility problem? — Without synchronisation, a write made by one thread may never become visible to another thread, or may become visible late or out of order.
  • How does garbage collection handle circular references? — Without any trouble. The JVM's collectors use reachability tracing from GC roots, not reference counting. Objects that reference each other in a cycle, but can't be reached from any root, are simply never marked, and they get collected.
  • How does the static keyword affect memory management? — Static fields are allocated once per class (per class loader), when the class is initialised. Since Java 8 they're stored on the heap, together with the class's java.lang.Class object.

Exception Design & Serialization Edge Cases — Interview Questions — open the lesson

  • Can static fields be serialized? — No. Serialization captures instance state, and static fields belong to the class. On deserialization, a static field simply has whatever value the class currently holds in the receiving JVM.
  • Are static fields serialized? (Asked again: prove it) — No. Here's a quick demonstration — class Config implements Serializable { static String region = "ap-south-1";
  • What happens if an exception is thrown during serialization? — writeObject aborts, and the exception propagates to the caller: NotSerializableException for a non-serializable object in the graph; InvalidClassException for class problems; a plain IOException for stream or disk failures; anything your custom writeObject throws.
  • A Serializable class has a member that isn't serializable. What happens, and how do you fix it? — Serialization throws java.io.NotSerializableException, naming the offending class. The fixes are: Make the member's class Serializable, if you own it; Mark the field transient (and rebuild it after deserialization, lazily or in readObject); Use custom…
  • What's the difference between NoClassDefFoundError and ClassNotFoundException? — Compared side by side in the full answer (table) — know each row.
  • What happens when an exception is thrown in a static initialiser? — The first attempt to initialise the class throws ExceptionInInitializerError, wrapping the cause. The class is then marked as erroneous.
  • When would you deliberately choose a checked exception over an unchecked one? — When the failure is expected, recoverable, and the caller can reasonably do something about it, so the compiler should force the caller to decide.
  • Have you used a finally block? Describe a scenario. — Typical real uses are guaranteed cleanup that isn't an AutoCloseable: releasing a ReentrantLock (lock.unlock() in finally); restoring the thread's state in a pool (MDC.clear(), threadLocal.remove()); resetting a flag or metrics timer; releasing a semaphore permit.
  • Has a finally block ever caused unexpected behaviour? — The common surprises: An exception thrown in finally masks the original exception from try. For example, close() fails and hides the real error. try-with-resources fixes this by attaching close failures as suppressed exceptions; return in finally swallows exceptions…
  • Why is catching Throwable bad practice? — Throwable includes Errors: OutOfMemoryError, StackOverflowError and LinkageError. After one of those, the JVM or application may be in an inconsistent state.

Java 8 Deep Dive & Stream Coding

Lambdas, Functional Interfaces & Method References — Interview Questions — open the lesson

  • What were the key features introduced in Java 8, and why did they matter? — Java 8 introduced: lambda expressions and method references; functional interfaces (java.util.function); the Stream API; default and static interface methods; …
  • What is a lambda expression, and what are its benefits? — A lambda is an anonymous function, (params) -> body, that implements the single abstract method of a functional interface.
  • What's the difference between a lambda and an anonymous class? — Compared side by side in the full answer (table) — know each row.
  • What's the difference between a lambda and an anonymous inner class? (Rephrased: when would you still choose the anonymous class?) — Choose an anonymous class when you must: implement an interface with more than one abstract method, or extend an abstract class; keep mutable state in fields between calls; refer to the object itself (this) inside its body, for example to unregister itself as a listener.
  • Can an interface with several default methods still be a functional interface? — Yes. A functional interface needs exactly one abstract method. Any number of default and static methods is fine, and so are abstract methods that just redeclare public Object methods (like equals).
  • What is a functional interface? — An interface with exactly one abstract method (a SAM type), which lambdas and method references can implement.
  • What are the predefined functional interfaces in Java 8? — They live in java.util.function. The core four and their families.
  • What are method references, and how do they relate to lambdas? — A method reference is a shorter form of a lambda whose body only calls an existing method. There are four kinds.
  • Can you use this and super inside a lambda? — Yes. Because a lambda doesn't introduce a new scope or object identity, this and super refer to the enclosing class instance and its superclass, exactly as they would in the surrounding method.
  • How can a lambda access variables outside its scope? — A lambda can capture local variables and parameters from the enclosing scope, but only if they're final or effectively final.
  • Can a lambda throw an exception? How do you handle checked exceptions in lambdas? — It can throw any unchecked exception. It can throw a checked exception only if the functional interface's method declares it, and the standard Function and Consumer don't. The options: Catch the exception inside the lambda, and handle it or wrap it; Wrap it in an…
  • What happens if you try to modify a local variable inside a lambda? — It's a compile error: "local variables referenced from a lambda expression must be final or effectively final".
  • Can you use synchronized inside a lambda? — Yes, a synchronized block inside the lambda body is perfectly legal: () -> { synchronized (lock) { … } }. What you can't do is mark the lambda itself synchronized, because lambdas have no method modifiers.

Default Methods, Backward Compatibility & Optional — Interview Questions — open the lesson

  • A class implements several interfaces with conflicting default methods. How do you resolve the conflict? — The compiler forces the class to override the conflicting method. Inside the override, you can delegate to a specific interface's version with InterfaceName.super.method(), or combine them.
  • What are default methods, and why were they introduced? — A default method is an interface method with a body (default keyword), which implementing classes inherit and may override.
  • How are static interface methods different from default methods? — Compared side by side in the full answer (table) — know each row.
  • How is Java 8 backward-compatible with earlier versions? — In three ways: Binary compatibility: class files compiled for older versions run unchanged on Java 8; Source compatibility: old code still compiles, with very rare exceptions; Language features built on existing concepts: lambdas target ordinary single-method interfaces (so…
  • Why did Java 8 introduce default methods, and what problem do they solve? — The interface evolution problem. Before Java 8, adding a method to a published interface broke every implementing class, both in source and at runtime (AbstractMethodError).
  • What is Optional, and how is it used? — Optional<T> is a container that is either empty, or holds a non-null value. It makes "there may be no result" explicit in a method's return type, and it offers functional methods for handling both cases, instead of scattered null checks.
  • How do you handle null values with Optional? — Wrap the possibly-null value with Optional.ofNullable(value), then transform it and supply defaults without explicit checks — String displayName = Optional.ofNullable(user.nickname())
  • What's the difference between Optional.of() and Optional.ofNullable()? — Optional.of(value) requires a non-null value. It throws NullPointerException immediately if the value is null, which is useful as an assertion.
  • Should you use Optional as a method parameter? — Generally no: It makes call sites awkward (search(Optional.empty())); It doesn't stop callers passing null for the Optional itself; It adds an allocation; Overloads, or a nullable parameter documented as such, are clearer.

Stream API Internals (Part 1) — Interview Questions — open the lesson

  • What is the Stream API, and how does it work internally? — A stream is a lazy, single-use pipeline over a data source: a source (a collection, array, generator or I/O), zero or more intermediate operations (filter, map, sorted), and one terminal operation (collect, reduce, forEach).
  • What's the difference between map and flatMap? — map is one-to-one: each element becomes exactly one new element. flatMap is one-to-many: each element becomes a stream of elements, and those streams are flattened into one.
  • map() vs flatMap(): when is each the right tool? (Rephrased, with Optional) — Use map when the function returns a plain value, and flatMap when it already returns a container (Stream, Optional), so you avoid nesting (Stream<Stream<T>>, Optional<Optional<T>>).
  • What's the difference between peek() and map(), and when should peek be used carefully? — map transforms elements, and its result replaces them in the stream. peek runs a side-effecting action and passes the same element along unchanged.
  • How do you filter a collection with streams? — Call stream(), then filter(predicate), then collect. filter keeps the elements for which the predicate returns true.
  • What's the difference between findFirst() and findAny()? — Both are short-circuiting terminal operations returning an Optional. findFirst respects encounter order, and always returns the first matching element.
  • What is the purpose of the Collectors class? — Collectors supplies ready-made mutable-reduction recipes for collect(): To collections: toList, toSet, toMap, toCollection, and the toUnmodifiable… variants; Joining strings: joining; Grouping and partitioning: groupingBy, partitioningBy; Aggregation:…
  • What's the significance of the forEach() method? — Java 8 added forEach in two places: Iterable.forEach(Consumer), a default method: internal iteration over any collection; Stream.forEach, a terminal operation.
  • How does Java 8 handle parallel processing with streams? — parallelStream(), or .parallel(), splits the source using its Spliterator, and processes the chunks as tasks in the common ForkJoinPool (with a size equal to the number of cores minus 1, plus the calling thread), then combines the partial results.
  • What's the purpose of the Predicate interface? — Predicate<T> represents a boolean-valued condition, boolean test(T t). It's used by filter, removeIf, anyMatch/allMatch/noneMatch, and takeWhile/dropWhile.

Stream API Internals (Part 2) — Interview Questions — open the lesson

  • How do you create an infinite stream? — With Stream.iterate(seed, next) (each element is derived from the previous one), or Stream.generate(supplier) (independent values).
  • What is the Function interface, and how is it used? — Function<T, R> represents a transformation, R apply(T t). It's what map takes. It composes: f.andThen(g) means apply f, then g, and f.compose(g) means apply g, then f.
  • How do you sort a collection with streams? — stream().sorted() for natural order, or sorted(comparator), then collect. The source isn't modified.
  • How do you apply a custom comparator in a stream pipeline? — Build the comparator with the Comparator factory methods, and pass it to sorted, max, min or collectors such as maxBy, or to a TreeMap supplier in toMap/groupingBy.
  • How does sorted() work internally, with natural ordering versus a comparator? — In both cases, sorted() is a stateful barrier. It buffers every upstream element (into an array or list), sorts the buffer once the upstream is exhausted, and only then pushes elements downstream.
  • What is reduce() used for? — reduce folds all the elements into a single value with an associative function. It has three forms: reduce(identity, accumulator): returns T; reduce(accumulator): returns Optional<T> (the stream may be empty); reduce(identity, accumulator, combiner): for reducing…
  • How does filter() work? — filter(Predicate) is a lazy, stateless intermediate operation. As each element reaches it during the terminal operation's single pass, the predicate is evaluated.
  • What's special about Collectors.toList()? How does it compare with Stream.toList()? — collect(Collectors.toList()) gathers the elements into a new List. In practice that's an ArrayList, but no guarantee is made about its type, mutability or thread-safety.
  • How does Stream.of() work? — Stream.of(T... values) creates a sequential, ordered stream from its arguments. Stream.of(single) creates a one-element stream.
  • What's the difference between limit() and skip()? — limit(n) keeps at most the first n elements, and short-circuits: upstream stops producing after n. skip(n) discards the first n elements, and passes the rest.
  • How do you convert a list to a map with streams? — collect(Collectors.toMap(keyMapper, valueMapper)). Know its three traps: Duplicate keys throw an IllegalStateException. Pass a merge function; null values throw an NPE (a HashMap.merge limitation); There's no ordering. Pass a map supplier (LinkedHashMap::new,…
  • What's the difference between Stream.iterate() and Stream.generate()? — iterate(seed, f) produces a sequence where each element depends on the previous one (seed, f(seed), f(f(seed))…), and it's ordered.
  • What's the difference between count(), sum() and reduce()? — count() returns the number of elements, as a long. It's on every stream, and can skip executing the pipeline when the size is known; sum() adds up the elements. It's only on primitive streams (IntStream, LongStream, DoubleStream), with no boxing, and it returns 0…

Stream Coding Problems (Level 2, Part 1) — Interview Questions — open the lesson

  • Find all the even numbers in a list. — List<Integer> evens = nums.stream().filter(n -> n % 2 == 0).toList();
  • Find the numbers that start with the digit 1. — List<Integer> startsWith1 = nums.stream() .filter(n -> String.valueOf(n).startsWith("1"))
  • Find the duplicate elements in a list. — Correct, side-effect-free versions — List<Integer> duplicates = nums.stream() .collect(Collectors.groupingBy(Function.identity(),…
  • Find the first element of a list. — Optional<Integer> first = nums.stream().findFirst();
  • Count the elements in a list. — long total = nums.stream().count();
  • Find the maximum value. — int max = nums.stream().max(Comparator.naturalOrder()).orElseThrow();
  • Find the first non-repeated character in a string. — String input = "Java articles are Awesome"; Optional<Character> firstUnique = input.chars()
  • Find the first repeated character in a string. — Be precise about the definition. Usually it means "the first character, scanning left to right, that has already appeared earlier".
  • Sort the values in ascending order. — List<Integer> ascending = nums.stream().sorted().toList();
  • Sort the values in descending order. — List<Integer> descending = nums.stream().sorted(Comparator.reverseOrder()).toList(); List<Integer>…
  • Contains duplicate: return true if any value appears at least twice. — static boolean containsDuplicate(int[] nums) { return Arrays.stream(nums).distinct().count() != nums.length;

Stream Coding Problems (Level 2, Part 2) — Interview Questions — open the lesson

  • How do you get the current date and time with the Java 8 Date-Time API? — LocalDate today = LocalDate.now();
  • How do you concatenate two streams? — Stream<String> all = Stream.concat(list1.stream(), list2.stream()); List<String> merged = Stream.of(list1,…
  • Cube the elements of a list, and keep the results greater than 50. — List<Integer> cubes = List.of(4, 5, 6, 7, 1, 2, 3).stream() .map(i -> i * i * i)
  • Sort an array, then convert it into a stream. — int[] arr = { 99, 55, 203, 99, 4, 91 }; Arrays.sort(arr);
  • Use map to convert strings to uppercase. — List<String> upper = names.stream().map(s -> s.toUpperCase(Locale.ROOT)).toList();
  • Convert a list of objects to a map, handling duplicate keys, in sorted order. — Use toMap with a merge function and a map supplier. Here, notes are keyed by tag name, and the map is ordered by tag ID, descending — record Note(int id, String tagName, long tagId) { } List<Note> notes = List.of(new Note(1, "note1", 11),…
  • Count each word in a list of strings. — List<String> names = List.of("AA", "BB", "AA", "CC"); Map<String, Long> counts = names.stream()
  • Find only the duplicate elements, with their counts. — Map<String, Long> duplicates = names.stream() .collect(Collectors.groupingBy(Function.identity(),…
  • If a list may be null or empty, iterate it safely with Optional and print each element. — Optional.ofNullable(notes) .orElseGet(List::of)
  • Find the maximum element in an array. — static int findMax(int[] arr) { return Arrays.stream(arr).max()
  • Count each character in a string. — String s = "string data to count each character"; Map<Character, Long> counts =…

Follow-up questions this topic invites — and their answers

Q: How should I use this list in the last week before an interview? A: Do one pass per day. Cover the answer text, say your answer out loud, then check it. Mark every question you could not answer crisply, and spend your study time only on the marked ones by opening the linked full answer. By the third pass the marked list should be short.

Q: The interviewer asks one of these basics — should I give only the one-liner? A: Lead with the one-liner, then add one concrete detail or example from your own work. At this level the follow-up usually probes the mechanism behind the basic answer, so be ready to go one layer deeper using the key points in the full lesson.

Q: Some answers here were corrected compared with common prep sheets — why? A: Several widely shared answers are outdated or wrong (for example, Java version details, removed Spring APIs, or SQL queries that miss edge cases). The full lessons call these out under "Common trap" — reading those is the fastest way to stand out from candidates who memorised the same sheets.

Next

Revise: Multithreading & Concurrency (2–5 Years Tier)

AI Tutor

Lesson: Revise: Core Java & Java 8+ (2–5 Years Tier)

Quick actions

AI responses can be inaccurate. Verify critical information.