Skip to content
C

Lambda Expressions

A lambda expression is a short, compact way of writing an anonymous (unnamed) block of code that represents a single method's behaviour, often used to implement a functional interface without writing a full class.


1. What is a Lambda Expression?

A lambda expression is a short, compact way of writing an anonymous (unnamed) block of code that represents a single method's behaviour, often used to implement a functional interface without writing a full class.

2. Why is it used?

Lambda expressions reduce boilerplate code significantly, especially when passing simple behaviour (like a comparison rule or an action) as an argument, instead of writing an entire separate class just for that one small piece of logic.

3. Real-Life Example

Think of leaving a short instruction note, like "water the plants," instead of writing a full formal document explaining who should do it, when, and why. A lambda expresses the needed action briefly, focusing only on what matters.

4. Syntax

java
(parameters) -> expression; (parameters) -> { statements; }

5. Example Program

java
interface Greeting { void sayHello(String name); } public class LambdaDemo { public static void main(String[] args) { Greeting greeting = (name) -> System.out.println("Hello, " + name); greeting.sayHello("Java Learner"); } }

Output:

Hello, Java Learner

6. Key Points to Remember

  • Lambda expressions can only be used with functional interfaces (interfaces with exactly one abstract method).
  • They make code shorter, especially for tasks like sorting or simple event handling.
  • Introduced in Java 8, lambda expressions are a major part of modern Java's more concise style.