Java 8-Java Core1 Comment

  • Lambda expressions

Lambda expressions are introduced in Java 8 and are touted to be the biggest feature of Java 8. Lambda expression facilitates functional programming, and simplifies the development a lot.

  • Syntax

A lambda expression is characterized by the following syntax : parameter -> expression body

Following are the important characteristics of a lambda expression :

  1. Optional type declaration − No need to declare the type of a parameter. The compiler can inference the same from the value of the parameter.
  2. Optional parenthesis around parameter − No need to declare a single parameter in parenthesis. For multiple parameters, parentheses are required.
  3. Optional curly braces − No need to use curly braces in expression body if the body contains a single statement.
  4. Optional return keyword − The compiler automatically returns the value if the body has a single expression to return the value. Curly braces are required to indicate that expression returns a value.
  • Lambda Expressions Example

Create the following Java program using editor and save in some folder like C:\>JAVA.

Java8Tester.java

Verify the Result

Compile the class using javac compiler as follows −

Now run the Java8Tester as follows −

It should produce the following output −

Following are the important points to be considered in the above example.

  1. Lambda expressions are used primarily to define inline implementation of a functional interface, i.e., an interface with a single method only. In the above example, we’ve used various types of lambda expressions to define the operation method of MathOperation interface. Then we have defined the implementation of sayMessage of GreetingService.
  2. Lambda expression eliminates the need of anonymous class and gives a very simple yet powerful functional programming capability to Java.

Scope

Using lambda expression, you can refer to final variable or effectively final variable (which is assigned only once). Lambda expression throws a compilation error, if a variable is assigned a value the second time.

Scope Example

Create the following Java program using editor and save in some folder like C:\>JAVA.

Java8Tester.java

Verify the Result

Compile the class using javac compiler as follows −

Now run the Java8Tester as follows −

It should produce the following output −


1 Comment on this article

Add a comment