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: 2–5 Years

Revise the Fresher Tier

  • Revise: Core Java Fundamentals (Fresher Tier)
  • Revise: Collections, Threads, Java 8 & Coding (Fresher Tier)
  • Revise: Spring Core, Spring Boot & Spring MVC (Fresher Tier)
  • Revise: Hibernate, SQL, Microservices, Maven & Git (Fresher Tier)

Intermediate Core Java

  • Intermediate OOP & Language Features — Interview Questions
  • Enums, Generics, Pass-by-Value & Imports — Interview Questions
  • Collections Internals & Scenarios — Interview Questions
  • JVM, Memory & Class Loading — Interview Questions
  • Exception Design & Serialization Edge Cases — Interview Questions

Java 8 Deep Dive & Stream Coding

  • Lambdas, Functional Interfaces & Method References — Interview Questions
  • Default Methods, Backward Compatibility & Optional — Interview Questions
  • Stream API Internals (Part 1) — Interview Questions
  • Stream API Internals (Part 2) — Interview Questions
  • Stream Coding Problems (Level 2, Part 1) — Interview Questions
  • Stream Coding Problems (Level 2, Part 2) — Interview Questions

Concurrency & Multithreading

  • Synchronization, Locks & Deadlocks — Interview Questions
  • Executors, ThreadLocal & Concurrent Collections — Interview Questions

Spring Framework In Depth

  • Bean Lifecycle, Contexts & Circular Dependencies — Interview Questions
  • Spring Bean Conflicts, AOP, Batch & Injection Styles — Interview Questions

Spring Boot In Depth & Scenarios

  • Spring Boot Internals & Auto-Configuration — Interview Questions
  • Spring Boot Configuration, Profiles & Secrets — Interview Questions
  • Spring Boot Data, Transactions & Caching — Interview Questions
  • Spring Boot Testing, Error Pages & Deployment — Interview Questions
  • Spring Boot Performance, Scaling & Resilience — Interview Questions
  • Spring Boot Async, Events & Messaging — Interview Questions
  • Spring Boot Security Scenarios — Interview Questions
  • Actuator, AOP, Spring Cloud & Distributed Tracing — Interview Questions
  • External APIs, Files, GraphQL & WebFlux — Interview Questions

Spring Security

  • Spring Security — OAuth2, CORS, CSRF & Access Rules — Interview Questions
  • Spring Security — Passwords, Filter Chain, Sessions & Debugging — Interview Questions

Apache Kafka

  • Kafka Architecture, Topics & ZooKeeper vs KRaft — Interview Questions
  • Kafka Producers, Consumers, Reliability & Streams — Interview Questions
  • Kafka Security, Connect & Core Scenarios — Interview Questions
  • Kafka Production Scenarios — Interview Questions

Git, Maven & Gradle (Level II)

  • Git Workflows, Rebase & Conflict Handling — Interview Questions
  • Git Recovery, Hooks, Tags & Collaboration — Interview Questions
  • Maven Builds, Multi-Module Projects & Dependency Resolution — Interview Questions
  • Maven Profiles, settings.xml, Plugins & Quality Gates — Interview Questions
  • Gradle Fundamentals, Migration & Dependencies — Interview Questions
  • Gradle Performance, Plugins, Testing & Publishing — Interview Questions

Deployment & CI/CD

  • Sessions, CI/CD Pipelines, Rollbacks & Secrets — Interview Questions
  • Migrations, Zero-Downtime Releases, Containers & Monitoring — Interview Questions

JUnit 5 & Mockito

  • JUnit 5 — Interview Questions
  • Mockito Basics — Interview Questions
  • Mockito Advanced & Tricky Questions — Interview Questions
Chaturmind
← Java Interview Prep: 2–5 Years

Revise the Fresher Tier

  • Revise: Core Java Fundamentals (Fresher Tier)
  • Revise: Collections, Threads, Java 8 & Coding (Fresher Tier)
  • Revise: Spring Core, Spring Boot & Spring MVC (Fresher Tier)
  • Revise: Hibernate, SQL, Microservices, Maven & Git (Fresher Tier)

Intermediate Core Java

  • Intermediate OOP & Language Features — Interview Questions
  • Enums, Generics, Pass-by-Value & Imports — Interview Questions
  • Collections Internals & Scenarios — Interview Questions
  • JVM, Memory & Class Loading — Interview Questions
  • Exception Design & Serialization Edge Cases — Interview Questions

Java 8 Deep Dive & Stream Coding

  • Lambdas, Functional Interfaces & Method References — Interview Questions
  • Default Methods, Backward Compatibility & Optional — Interview Questions
  • Stream API Internals (Part 1) — Interview Questions
  • Stream API Internals (Part 2) — Interview Questions
  • Stream Coding Problems (Level 2, Part 1) — Interview Questions
  • Stream Coding Problems (Level 2, Part 2) — Interview Questions

Concurrency & Multithreading

  • Synchronization, Locks & Deadlocks — Interview Questions
  • Executors, ThreadLocal & Concurrent Collections — Interview Questions

Spring Framework In Depth

  • Bean Lifecycle, Contexts & Circular Dependencies — Interview Questions
  • Spring Bean Conflicts, AOP, Batch & Injection Styles — Interview Questions

Spring Boot In Depth & Scenarios

  • Spring Boot Internals & Auto-Configuration — Interview Questions
  • Spring Boot Configuration, Profiles & Secrets — Interview Questions
  • Spring Boot Data, Transactions & Caching — Interview Questions
  • Spring Boot Testing, Error Pages & Deployment — Interview Questions
  • Spring Boot Performance, Scaling & Resilience — Interview Questions
  • Spring Boot Async, Events & Messaging — Interview Questions
  • Spring Boot Security Scenarios — Interview Questions
  • Actuator, AOP, Spring Cloud & Distributed Tracing — Interview Questions
  • External APIs, Files, GraphQL & WebFlux — Interview Questions

Spring Security

  • Spring Security — OAuth2, CORS, CSRF & Access Rules — Interview Questions
  • Spring Security — Passwords, Filter Chain, Sessions & Debugging — Interview Questions

Apache Kafka

  • Kafka Architecture, Topics & ZooKeeper vs KRaft — Interview Questions
  • Kafka Producers, Consumers, Reliability & Streams — Interview Questions
  • Kafka Security, Connect & Core Scenarios — Interview Questions
  • Kafka Production Scenarios — Interview Questions

Git, Maven & Gradle (Level II)

  • Git Workflows, Rebase & Conflict Handling — Interview Questions
  • Git Recovery, Hooks, Tags & Collaboration — Interview Questions
  • Maven Builds, Multi-Module Projects & Dependency Resolution — Interview Questions
  • Maven Profiles, settings.xml, Plugins & Quality Gates — Interview Questions
  • Gradle Fundamentals, Migration & Dependencies — Interview Questions
  • Gradle Performance, Plugins, Testing & Publishing — Interview Questions

Deployment & CI/CD

  • Sessions, CI/CD Pipelines, Rollbacks & Secrets — Interview Questions
  • Migrations, Zero-Downtime Releases, Containers & Monitoring — Interview Questions

JUnit 5 & Mockito

  • JUnit 5 — Interview Questions
  • Mockito Basics — Interview Questions
  • Mockito Advanced & Tricky Questions — Interview Questions
HomeLearnJava Interview PrepJava Interview Prep: 2–5 YearsJava 8 Deep Dive & Stream Coding
✓ FreeIntermediate· 8 min read

Lambdas, Functional Interfaces & Method References — Interview Questions

Java 8 features at depth, how lambdas work (invokedynamic) and differ from anonymous classes, functional interfaces with default methods, the built-in java.util.function types, method references, this/super in lambdas, variable capture, checked exceptions in lambdas, and synchronization inside lambdas.

Published September 25, 2026


How to use this lesson

At 2–5 years, "what is a lambda?" isn't enough. Explain how lambdas are compiled, what they capture, and how they behave differently from anonymous classes (this, scope, serialization). A couple of those details will set you apart.

Q1. What were the key features introduced in Java 8, and why did they matter?

Short answer: Java 8 introduced:

  • lambda expressions and method references;
  • functional interfaces (java.util.function);
  • the Stream API;
  • default and static interface methods;
  • Optional;
  • the java.time API;
  • CompletableFuture;
  • Nashorn, and Metaspace in place of PermGen.

Together they brought functional-style, declarative data processing to Java, and made asynchronous composition practical. They also let the JDK evolve existing interfaces (such as Collection.stream()) without breaking every implementation.

Learn it in depth → Lambda Expressions

Q2. What is a lambda expression, and what are its benefits?

Short answer: A lambda is an anonymous function, (params) -> body, that implements the single abstract method of a functional interface. Its benefits: much less boilerplate, behaviour passed as data (strategies, callbacks, comparators), and it's the foundation of streams and CompletableFuture pipelines.

Comparator<Order> byTotal = (a, b) -> a.total().compareTo(b.total());
Predicate<Order> isLarge = o -> o.total().compareTo(new BigDecimal("10000")) > 0;
Runnable task = () -> log.info("tick");

Key points to cover:

  • How it's compiled: the lambda body becomes a private synthetic method. The call site uses invokedynamic with LambdaMetafactory to create the functional-interface instance at runtime. No .class file is generated per lambda, and non-capturing lambdas are cached as singletons.

Q3. What's the difference between a lambda and an anonymous class?

Short answer:

LambdaAnonymous class
Can implementOnly a functional interfaceAny interface (several methods) or abstract class
this meansThe enclosing instanceThe anonymous object itself
New scope?No: can't redeclare the enclosing method's local namesYes: can shadow variables
State (fields)NoneCan have fields
Compilationinvokedynamic + a synthetic methodA separate Outer$1.class
Instance per evaluationNon-capturing lambdas are reusedAlways a new object
class Button {
    String name = "save";
    void wire() {
        Runnable l = () -> System.out.println(this.name);            // "save": the enclosing Button
        Runnable a = new Runnable() {
            String name = "anon";
            public void run() { System.out.println(this.name); }     // "anon": the anonymous object
        };
    }
}

Q4. What's the difference between a lambda and an anonymous inner class? (Rephrased: when would you still choose the anonymous class?)

Short answer: Choose an anonymous class when you must:

  1. implement an interface with more than one abstract method, or extend an abstract class;
  2. keep mutable state in fields between calls;
  3. refer to the object itself (this) inside its body, for example to unregister itself as a listener.

Otherwise, use a lambda (or a method reference).

Q5. Can an interface with several default methods still be a functional interface?

Short answer: 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). Comparator is the best example: one abstract method (compare), plus many default methods (reversed, thenComparing, …).

@FunctionalInterface
interface Rule {
    boolean test(Order o);                                  // the single abstract method
    default Rule and(Rule other) { return o -> test(o) && other.test(o); }
    default Rule negate() { return o -> !test(o); }
    boolean equals(Object obj);                             // an Object method: doesn't count
}

Common trap: answering "no". The source of this question in many prep sheets even contradicts itself. The rule counts abstract methods only.

Q6. What is a functional interface?

Short answer: An interface with exactly one abstract method (a SAM type), which lambdas and method references can implement. @FunctionalInterface is optional, but it makes the compiler enforce the rule, so nobody accidentally adds a second abstract method later.

Key points to cover:

  • Any SAM interface qualifies, even pre-Java 8 ones: Runnable, Callable, Comparator, and Spring's RowMapper and TransactionCallback.

Q7. What are the predefined functional interfaces in Java 8?

Short answer: They live in java.util.function. The core four and their families:

InterfaceSignatureTypical use
Supplier<T>() → TLazy values, factories (orElseGet)
Consumer<T> / BiConsumer<T,U>T → voidSide effects (forEach)
Function<T,R> / BiFunction<T,U,R>T → RTransformations (map)
Predicate<T> / BiPredicate<T,U>T → booleanFilters (filter, removeIf)
UnaryOperator<T> / BinaryOperator<T>T → T, (T,T) → TreplaceAll, reduce
Primitive variantsIntPredicate, ToLongFunction, IntBinaryOperator, …Avoid boxing

Key points to cover:

  • They're composable: Function.andThen/compose, Predicate.and/or/negate/not, Comparator.thenComparing.

Q8. What are method references, and how do they relate to lambdas?

Short answer: A method reference is a shorter form of a lambda whose body only calls an existing method. There are four kinds:

KindExampleEquivalent lambda
Static methodInteger::parseInts -> Integer.parseInt(s)
Instance method of a particular objectSystem.out::printlnx -> System.out.println(x)
Instance method of an arbitrary object of a typeString::toUpperCases -> s.toUpperCase()
ConstructorArrayList::new() -> new ArrayList<>()

Key points to cover:

  • A bound reference (System.out::println, this::handle) evaluates its receiver once, when the reference is created. A lambda re-evaluates it on each call.

Learn it in depth → Method References

Q9. Can you use this and super inside a lambda?

Short answer: 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. (Inside an anonymous class, this would be the anonymous object instead.)

class ReportService extends BaseService {
    void schedule(ScheduledExecutorService ses) {
        ses.schedule(() -> super.logStart(this.name()), 5, TimeUnit.SECONDS);   // enclosing object and its parent
    }
}

Key points to cover:

  • Capturing this keeps the enclosing object reachable for as long as the lambda is. Be careful with long-lived callbacks.

Q10. How can a lambda access variables outside its scope?

Short answer: A lambda can capture local variables and parameters from the enclosing scope, but only if they're final or effectively final. The lambda receives a copy of the value. It can also read and modify fields (instance or static), because those are accessed through the object, not copied.

Key points to cover:

  • Why the restriction exists: captured locals are copied, possibly to another thread. Allowing either side to change them would create two diverging copies, and hidden race conditions. Fields don't have this problem, but mutating them from lambdas (especially in parallel streams) is still a concurrency bug waiting to happen.

Q11. Can a lambda throw an exception? How do you handle checked exceptions in lambdas?

Short answer: 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 unchecked exception, such as UncheckedIOException.
  • Define your own functional interface that declares the exception.
  • Collect errors as values (a Result/Either type) instead of throwing.
@FunctionalInterface
interface ThrowingFunction<T, R> { R apply(T t) throws Exception; }

static <T, R> Function<T, R> unchecked(ThrowingFunction<T, R> f) {
    return t -> {
        try { return f.apply(t); }
        catch (RuntimeException e) { throw e; }
        catch (Exception e) { throw new CompletionException(e); }
    };
}

List<String> contents = paths.stream().map(unchecked(Files::readString)).toList();

Q12. What happens if you try to modify a local variable inside a lambda?

Short answer: It's a compile error: "local variables referenced from a lambda expression must be final or effectively final". The same applies to modifying the variable after the lambda captures it anywhere in the method.

int count = 0;
list.forEach(x -> count++);                       // ❌ compile error

AtomicInteger counter = new AtomicInteger();      // workaround, but prefer a stream reduction:
list.forEach(x -> counter.incrementAndGet());
long count2 = list.stream().filter(this::isValid).count();   // ✅ idiomatic

Common trap: using a one-element array (int[] c = {0}) to sneak around the rule. It compiles, but it isn't thread-safe in parallel streams, and it hides intent.

Q13. Can you use synchronized inside a lambda?

Short answer: 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. And synchronized (this) inside a lambda locks the enclosing instance, not the lambda.

Object lock = new Object();
Runnable increment = () -> {
    synchronized (lock) {        // ✅ compiles and works
        sharedCounter++;
    }
};

Common trap: claiming "synchronized can't be used in lambdas". It's a widespread wrong answer. Better design still avoids shared mutable state: use AtomicLong/LongAdder, or a reduction.

Follow-up questions this topic invites — and their answers

Q: Are lambdas objects? Do they have a class? A: Yes. At runtime, a lambda is an instance of a hidden class that implements the functional interface. Don't rely on its identity, toString() or class name.

Q: Can a lambda be serialized? A: Only if its target type is Serializable (for example, a cast to (Runnable & Serializable)). That's fragile, and generally discouraged.

Q: What's the performance cost of lambdas? A: Tiny. Non-capturing lambdas are cached singletons. Capturing lambdas allocate a small object, which escape analysis often eliminates. The first call to each lambda has a one-off bootstrap cost.

Q: What does Predicate.not add? A: Since Java 11, Predicate.not(String::isBlank) negates a method reference, so filter(not(String::isBlank)) reads cleanly.

Previous

Exception Design & Serialization Edge Cases — Interview Questions

Next

Default Methods, Backward Compatibility & Optional — Interview Questions

AI Tutor

Lesson: Lambdas, Functional Interfaces & Method References — Interview Questions

Quick actions

AI responses can be inaccurate. Verify critical information.