Java Program Addition Of Two Numbers – 3 Ways

Java Program to print Addition Of Two Numbers is quite simple. we also write the program in three ways.

Using method reference:-
here we make list and pass two integer value.after that stream this list and mapToInt method returns an IntStream consisting of the results of applying the given function to the elements of this stream.
intValue() of Integer class that is present inside java.lang package is an inbuilt method in java that returns the value of this integer as an int which is inherited from
we can replace a method reference for your lambda expression whenever you are just referring to a method with a lambda expression.
mapToInt : IntStream mapToInt(ToIntFunction mapper)
sum method : java.util.stream.IntStream.sum()

using method body:-
here we create static test method int type and pass two parameter,it add then return value.

using Lambda method:-
A lambda expression is a short block of code which takes in parameters and returns a value.
here first we create one interface class and declare one add method with two parameter.now implement this add method from lambda expression.through lambda method add this two parameter and call add method from interface class.

				
					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 referenece
		List<Integer> al = Arrays.asList(2, 3);
		int m = al.stream().mapToInt(Integer::intValue).sum();
		System.out.println("addition from metho 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 metho reference:- 5
addition from method:-3
sum of (2,4):- 6

Leave a Comment

Your email address will not be published. Required fields are marked *