Java 8: Lambda expressions

Java 8 features
 Lambda expressions |   Method references |   Default methods |   forEach loop |   By date 

Lambda expression is included in JSE8. It provides implementation of a functional interface, which is an interface that contains only one abstract method, but it may contain one or more default methods or static methods. This new feature is important, because it helps to write less code by programming. For more info click here to read Oracle’s explanation.

The syntax of lambda expression

  1. List parameters enclosed in parentheses, example:  (String text, double salary)
  2. The arrow token:  ->
  3. The body, which contains a single expression or a statement block.

Example 1: Lambda expression
What happens if the following code is compiled and run?

MyInterface.java

public interface MyInterface
{
  int x = 8;
  
  void getMessage(String str, int i);
}

MyClass.java

 
public class MyClass
{
  int x = 2;
  
  public static void main(String[] args)
  {
    MyClass mc = new MyClass();
    /* Lambda expression 
     * using two parameters
     */
    MyInterface mi = (str, i) ->
    {
      int i2 = i + mc.x;
      System.out.print(str + i2);
    };
    mi.getMessage("y", 5);
    System.out.print(mi.x);
  }
}
Author: Sar Maroof

Select the correct answer.


Answer explanation

  1. The statement mi.getMessage(“y”, 5); invokes the overridden method.
  2. The statement System.out.print(str + i2); writes y and the value of i2 = i + mc.x.
  3. The value mc.x = 2, because x is the instance variable of the class MyClass.
  4. So, i2 = 5 + 2 = 7.
  5. The statement System.out.print(mi.x); writes the value of the variable x of the interface MyInterface. So, x = 8.

The correct answer is: d.

How to write the previous code in Java 7 or older Java versions

The interface remains the same as follows:

MyInterface.java

public interface MyInterface
{
  int x = 8;
  
  void getMessage(String str, int i);
}

See the different between the following code and the previous code, which used lambda expression.

MyClass.java

public class MyClass
{
  int x = 2;
  
  public static void main(String[] args)
  {
    MyClass mc = new MyClass();
    MyInterface mi = new MyInterface()
    {
      public void getMessage(String str, int i)
      {
        int i2 = i + mc.x;
        System.out.print(str + i2);
      }
    };
    mi.getMessage("y", 5);
    System.out.print(mi.x);
  }
}

The output of this code is also y78





Sar Maroof is a professional software development teacher, gives master classes and publishes technical articles. He is also an expert software developer and worked for several big as well as small companies and later as a freelancer.

 Subscribe to Sar Maroof's RSS feeds!
 Mail this page to a friend!
 Bookmark this page!

Leave a Reply

Your email address will not be published. Required fields are marked *