Learn how to add two numbers in Java using three different approaches. We will use a method reference, a normal method, and a lambda expression.
Code Explanation (Step-by-Step)
Using Method Reference
- First, create a list and store two integer values in it.
- Convert the list into a stream using the stream() method.
- The mapToInt() method converts the stream elements into an IntStream .
- Integer::intValue is a method reference that converts each Integer object to a primitive int.
- The sum() method calculates the total of all elements in the IntStream.
Using Method Body
- Create a static method named test() with two integer parameters.
- Inside the method, add both numbers using the + operator.
- Return the result to the calling test() method.
- Call the test() method from the main() method and print the result.
Using Lambda Expression
- First, create a functional interface named Addable.
- Declare an add() method that accepts two integer parameters.
- Implement the add() method using a lambda expression.
- The lambda expression adds the two numbers and returns the result.
- Call the add() method through the interface reference and print the output.
import java.util.Arrays;
import java.util.List;
interface Addable {
int add(int a, int b);
}
public class AdditionMain {
public static int test(int a, int b) {
return a + b;
}
public static void main(String[] args) {
// From method reference
List al = Arrays.asList(2, 3);
int m = al.stream().mapToInt(Integer::intValue).sum();
System.out.println("Addition from method reference: " + m);
// From method body
System.out.println("Addition from method: " + test(1, 2));
// From lambda expression
Addable abl = (x, y) -> x + y;
int result = abl.add(2, 4);
System.out.println("Sum of (2, 4): " + result);
}
}
Output :-
Addition from method reference: 5
Addition from method: 3
Sum of (2, 4): 6
How to Add Two Numbers in Java Using Scanner
import java.util.Scanner;
public class AdditionMain {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter first number:");
int num1 = sc.nextInt();
System.out.println("Enter second number:");
int num2 = sc.nextInt();
int sum = num1 + num2;
System.out.println("Sum of two numbers: " + sum);
sc.close();
}
}