Part 2 – Lambda vs Anonymous class in Java 8

U1

Lambda vs Anonymous class in Java 8

What have we learned so far
1. Lambda Expression in Java 8
PART 1 – LAMBDA EXPRESSION IN JAVA 8


Lets compare the difference in between Lambda Expression and Anonymous class.
1. Syntax
Anonymous class:

package com.onlyfullstack;
public class LambdaVsAnonymousClass {

 public static void main(String[] args) {
  Runnable runnable = new  Runnable() {
   @Override
   public void run() {
    System.out.println("Anonymous class");
   }
  };
  
  Thread thread = new Thread(runnable);
  thread.start();
 }
}

Lambda:

package com.onlyfullstack;

public class LambdaVsAnonymousClass {

 public static void main(String[] args) {
  Runnable runnable = () -> System.out.println("Lambda Expression");
  
  Thread thread = new Thread(runnable);
  thread.start();
 }
}

2. Implementation
Anonymous class can be used to implement any interface with any number of abstract methods.
Lambda Expression will only work with SAM(Single Abstract Method) types. That is interfaces with only a single abstract method which is also called as Functional Interface. It would fail as soon as your interface contains more than 1 abstract method.

3. Compilation
Anonymous class : Java creates two class files for LambdaVsAnonymousClass java file as
LambdaVsAnonymousClass.class     – contains the main program
LambdaVsAnonymousClass$1.class – contains an anonymous class

2 Untitled

Lambda Expression: With Lambda expression compiler will create only 1 class file as below.

Untitled1

So Java will create the new class file for each Anonymous class used.

4. Performance
Anonymous classes

Anonymous classes are processed by the compiler as a new subtype for the given class or interface so there will be generated a new class file for each anonymous class used. When the application is launched each class which is created for the Anonymous class will be loaded and verified. This process is quite a time consuming when you have a large number of anonymous class.

Lambda expressions

Instead of generating direct bytecode for lambda (like proposed anonymous class syntactic sugar approach), compiler declares a recipe (via invokeDynamic instructions) and delegates the real construction approach to runtime.

So Lambda expressions are faster than the Anonymous classes as they are only executed when they are called.

Lets go to our next tutorial where we will discuss below points :

– Why Lambda Expression only supports final variables in the body?
– How to use the final variable in Lambda Expression?
– What is the effective final variable in Java 8?