Write a Java program using Lambda Expression to find the sum of two integers
The java program that demonstrates the use of lambda expressions to calculate the sum of two numbers. Here's an explanation of the code:
- import java.util.Scanner;: This line imports the Scanner class from the java.util package, which is used to read input from the user.
- The LambdaSum class is defined, which contains the main method, where the program's execution begins.
- Inside the main method:
- Scanner in = new Scanner(System.in);: It creates a Scanner object named in to read input from the standard input (keyboard).
- SumCalculator calculator = (a, b) -> a + b; : This line creates a lambda expression that represents the SumCalculator interface. The lambda expression takes two integer parameters, a and b, and calculates their sum by using the a + b expression. It's effectively a shorthand way of implementing the sum method from the SumCalculator interface.
- System.out.println("Enter the Two Numbers : ");: This line prompts the user to enter two numbers.
- int num1 = in.nextInt(); and int num2 = in.nextInt();: These lines use the Scanner object in to read two integer values entered by the user.
- int result = calculator.sum(num1, num2);: This line uses the lambda expression calculator to calculate the sum of num1 and num2 and stores the result in the result variable.
- System.out.println("Sum : " + result);: This line prints the result of the sum to the standard output.
- The SumCalculator interface is defined with a single abstract method, int sum(int a, int b);. The lambda expression in the main method implements this method.
When you run the program, it will ask the user to enter two numbers, calculate their sum using the lambda expression, and then display the result. The lambda expression simplifies the code required to create a functional interface implementation, making it more concise and readable.
Source Code
import java.util.Scanner;
public class LambdaSum
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
SumCalculator calculator = (a, b) -> a + b;
System.out.println("Enter the Two Numbers : ");
int num1 = in.nextInt();
int num2 = in.nextInt();
int result = calculator.sum(num1, num2);
System.out.println("Sum : " + result);
}
}
interface SumCalculator
{
int sum(int a, int b);
}
Output
Enter the Two Numbers :
18
23
Sum : 41