- Home
- Interview Questions
- Java
- 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
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 aninvokedynamicinstruction. On first execution,LambdaMetafactorygenerates 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
AtomicIntegeras a mutable counter inside a stream lambda. This hides side effects and breaks with parallel streams. Usereduce,sumor 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
equalsare 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
invokedynamicfor 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
- How does HashMap work internally, including collisions, resizing and treeification in Java 8? · 1 ans
- How do you implement a generic interface and its functions in Java? · 1 ans
- How does the JVM manage memory for Java applications? · 1 ans
- How do abstract classes differ from interfaces in Java? · 1 ans
- How do final variables differ from static final variables? · 1 ans
Related Questions
- What makes an interface a functional interface, and what does @FunctionalInterface actually do? · Java · 1 ans
- How does HashMap work internally, including collisions, resizing and treeification in Java 8? · Java · 1 ans
- What is the difference between HashSet, LinkedHashSet and TreeSet, and when would you use each? · Java · 1 ans
- Why does a for loop with var and setTimeout print the same value every time? · JavaScript · 1 ans
- How do you write a Python decorator that accepts its own arguments? · Python · 1 ans
- Why do lambdas created inside a loop all return the last loop value in Python? · Python · 1 ans
- How do you implement a generic interface and its functions in Java? · Java · 1 ans
- What are the constraints in Java generics and why are they used? · Java · 1 ans
🙋 Was this asked in your interview?
Which company? (optional — adds this question to the company's page)