Lambda Expression:- A Lambda Expression in Java 8 is a short and clear way to provide the implementation of a functional interface . It reduces boilerplate code and makes programs easier to read. In this example, we use a lambda expression to print a message in Java.
Print Hello World Using Lambda Expression in Java 8 :-
- PrintHello is a functional interface because it contains only one abstract method .
- The print() method is used to display a message.
- First, the interface method is implemented using an anonymous inner class.
- Then, the same method is implemented using a lambda expression.
- When the print() method is called, the message is displayed on the console.
interface PrintHello {
public void print();
}
public class CountChar {
public static void main(String[] args) {
// anonymous inner class
PrintHello test = new PrintHello() {
public void print() {
System.out.println("printing from anonymous inner class");
}
};
test.print();
// using a lambda expression
PrintHello hello = () -> {
System.out.println("Hello from lambda expression");
};
hello.print();
}
}
Output:-
printing from anonymous inner class
Hello from lambda expression
FAQ :
Can I print Hello World using lambda expression in Java?
Yes, you can print Hello World using a lambda expression by implementing a functional interface method.
What is the difference between anonymous class and lambda expression?
An anonymous class uses more code, while a lambda expression provides a shorter and cleaner syntax.