The sum() method of Java Integer class add the two specified integers values. It returns the same result as given by + operator.
Syntax
public static int sum (int a, int b)
Parameters
The parameters ‘a’ and ‘b’ represent the first and second operands.
Return Value
This method returns the sum of ‘a’ and ‘b’.
Example 1
1 2 3 4 5 6 7 8 9 10 11 |
public class JavaIntegerSumExample1 { public static void main(String[] args) { Integer a = 87; Integer b = 98; //add the two integer values int val = Integer.sum(a, b); System.out.println(a+"+"+b+" = "+val); } } |
Output
1 2 3 |
87+98 = 185 |
Example 2
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
import java.util.Scanner; public class JavaIntegerSumExample2 { public static void main(String[] args) { int temp,sum=0; Scanner scanner= new Scanner(System.in); System.out.print("Enter the total numbers to be added : "); int num=scanner.nextInt(); int[] a= new int[num]; System.out.println("Enter "+num+" elements."); for (int i=0;i<a.length;i++){ a[i]=scanner.nextInt(); } for (int i=0;i<a.length-1;i++) { sum=Integer.sum(a[i],a[i+1]); temp=sum; a[i+1]=temp; } System.out.println("Sum : "+sum); } } |
Output
1 2 3 4 5 6 7 8 9 10 |
Enter the total numbers to be added : 5 Enter 5 elements. 25 25 25 25 25 Sum : 125 |
Example 3
1 2 3 4 5 6 7 8 9 10 11 |
public class JavaIntegerSumExample3 { public static void main(String[] args) { Integer a = Integer.MAX_VALUE; Integer b = Integer.MIN_VALUE; //add the two integer values int val = Integer.sum(a, b); System.out.println(a+" + ("+b+" ) = "+val); } } |
Output
1 2 3 |
2147483647 + (-2147483648 ) = -1 |