1. Home
  2. Interview Questions
  3. Java
  4. How is a lambda different from an anonymous inner class in J…

Try answering first

In a real interview nobody shows you the answer. Think it through (or type it), then reveal the answers and rate yourself.

1 Answer

0 0
InterviewQuestions Team ✔ Expert answer ✔ Best answer ·

Short answer: A lambda does not create a new scope, so this refers to the enclosing instance and you cannot redeclare enclosing local names. It is compiled into a private method linked at runtime through invokedynamic, not a separate .class file. An anonymous class is a real class instance: it has its own this, can hold state, and can implement multi-method interfaces or extend classes.

Detailed explanation

1. Meaning of this and scope. Inside an anonymous class, this is the anonymous object. Inside a lambda, this is the object of the enclosing method, because a lambda is lexically scoped like a normal block. For the same reason, a lambda parameter or local variable cannot have the same name as a local in the enclosing method. That is a compile error. An anonymous class can shadow such names because it opens a new class scope.

2. What it can implement. A lambda can only target a functional interface. An anonymous class can extend an abstract or concrete class, call a superclass constructor with arguments, implement an interface with several abstract methods, and declare its own fields to keep mutable state between calls.

3. Variable capture. Both can read enclosing local variables only if they are final or effectively final. Since Java 8 this applies to anonymous classes too; earlier versions required the explicit final keyword. Locals are captured by value. The lambda gets a copy, because the original stack variable may no longer exist when the lambda runs. If mutation were allowed, the copy and the original would silently differ, and lambdas passed to other threads would race. Instance fields can be modified, because what is captured is this, not the field.

4. Compilation and runtime.

  • An anonymous class compiles to its own file, for example Outer$1.class. Each evaluation of the expression creates a new object.
  • A lambda body compiles to a private synthetic method in the same class, typically named like lambda$main$0. The creation point becomes an invokedynamic instruction. On first execution, LambdaMetafactory generates an implementation class at runtime. This means fewer class files to load at startup, and the JVM is free to choose the strategy.
  • For a non-capturing lambda, current JVMs usually return the same instance on every evaluation. This is an implementation detail, so never rely on lambda identity.

5. Memory. An anonymous class created in an instance context has traditionally held a reference to the outer object even when it does not use it. That reference can keep large objects, such as an Android Activity or a big service, alive. A lambda captures this only if its body actually uses instance members.

Example

public class Greeter {
    private String name = "Outer";
    private int calls = 0;

    public void demo() {
        int limit = 3;               // effectively final

        Runnable anon = new Runnable() {
            private String name = "Anon";      // own state allowed
            public void run() {
                System.out.println(this.name);  // prints Anon
            }
        };

        Runnable lambda = () -> {
            System.out.println(this.name);      // prints Outer
            calls++;                            // OK: field via captured this
            // limit++;                         // error: must be effectively final
            // int limit = 5;                   // error: already defined in scope
        };

        anon.run();
        lambda.run();
    }

    public static void main(String[] args) {
        new Greeter().demo();
    }
}

Compile this and you will see Greeter$1.class for the anonymous class. No extra file appears for the lambda. Running javap -c -p Greeter shows a private lambda$demo$0 method and an invokedynamic instruction.

Common mistakes

  • Saying a lambda is "just syntactic sugar for an anonymous class". The scoping rules, the meaning of this, and the bytecode are all different.
  • Working around effectively final by using a one-element array or AtomicInteger as a mutable counter inside a stream lambda. This hides side effects and breaks with parallel streams. Use reduce, sum or a collector instead.
  • Assuming two lambdas with identical bodies are equal, or using a lambda as a map key or lock object. Lambda identity and equals are not specified.
  • Claiming anonymous classes could mutate captured locals before Java 8. They always needed final; Java 8 only removed the need to write the keyword.

Follow-up questions

  • When would you deliberately choose an anonymous class over a lambda in modern Java?
  • Why does the JVM use invokedynamic for lambdas instead of generating inner classes at compile time?
  • How do lambdas and method references appear in stack traces, and how does that affect debugging?

Interview tip: Lead with the this difference and back it up with the javap observation. Showing the bytecode-level difference separates experienced candidates from those who only know the syntax.

Reviewed by the Interview Questions editorial team · Last updated

How well did you know this?

Rate yourself to track progress, build your streak and get “didn't know” questions in your revision list.

Your Answer

More hard Java questions

All hard questions →

Related Questions

‹
Q17 of 18 · Java
Next ›

Interview Questions

Free interview questions and answers, MCQ practice, online tests, mock interviews and group discussions — everything you need to crack your next interview.
📍 Dasardot LLC
1309 Coffeen Avenue STE 1200
Sheridan, Wyoming 82801
USA