Java 8 - Lambda Expressions
Java 8 - 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.
Optional type declaration − No need to declare the type of a parameter. The compiler can
inference the same from the value of the parameter.
Optional curly braces − No need to use curly braces in expression body if the body
contains a single statement.
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.
Java8Tester.java
Live Demo
public class Java8Tester {
https://www.tutorialspoint.com/java8/java8_lambda_expressions.htm 1/4
8/10/22, 8:35 PM Java 8 - Lambda Expressions
//without parenthesis
//with parenthesis
greetService1.sayMessage("Mahesh");
greetService2.sayMessage("Suresh");
interface MathOperation {
interface GreetingService {
C:\JAVA>javac Java8Tester.java
https://www.tutorialspoint.com/java8/java8_lambda_expressions.htm 2/4
8/10/22, 8:35 PM Java 8 - Lambda Expressions
C:\JAVA>java Java8Tester
10 + 5 = 15
10 - 5 = 5
10 x 5 = 50
10 / 5 = 2
Hello Mahesh
Hello Suresh
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 any 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 any editor of your choice in, say, C:\> JAVA.
Java8Tester.java
Live Demo
public class Java8Tester {
System.out.println(salutation + message);
greetService1.sayMessage("Mahesh");
interface GreetingService {
https://www.tutorialspoint.com/java8/java8_lambda_expressions.htm 3/4
8/10/22, 8:35 PM Java 8 - Lambda Expressions
C:\JAVA>javac Java8Tester.java
C:\JAVA>java Java8Tester
Hello! Mahesh
https://www.tutorialspoint.com/java8/java8_lambda_expressions.htm 4/4