Signup/Sign In

Java Integer sum() Method

Java sum() method is a part of the Integer class of the java.lang package. This method returns the numerical sum of the values passed as arguments (i.e simply adds the two numbers passed as argument in accordance with the + operator).

Syntax:

public static int sum(int a, int b)  

Parameters:

The parameters passed includes the two integer values whose addition is to be returned.

Returns:

Returns the sum of the two integer values passed as parameters.

Example 1:

Here, some positive and negative numbers are taken for a better understanding of the method.

import java.lang.Integer;

public class StudyTonight
{  
    public static void main(String[] args) 
    {          
        int a = 10;  
        int b = 29;  
        int c = -67;
        // It will return the sum of a and b
        System.out.println("The sum of a and b is = " + Integer.sum(a, b));  
        // It will return the sum of a and b
        System.out.println("The sum of a and b is = " + Integer.sum(b, c));  
    }  
}


The sum of a and b is = 39
The sum of a and b is = -38

Example 2:

Here is a user-defined example where anyone using this code can put a value of his choice and get the equivalent output.

import java.util.Scanner;  

public class StudyTonight
{  
    public static void main(String[] args) 
    {  
        try
        {
            System.out.println("Enter the two values : ");  
            Scanner sc = new Scanner(System.in);  
            int a = sc.nextInt();  
            int b = sc.nextInt();  
            // will return the sum of a and b. 
            System.out.println("sum is = " + Integer.sum(a, b));  
        }
        catch(Exception e)
        {
            System.out.println("Invalid Input");
        }      
    }  
}  


Enter the two values :
67 54
sum is = 121
****************************
Enter the two values :
55 -33
sum is = 22
****************************
Enter the two values :
0x56 0x767
Invalid Input

Live Example:

Here, you can test the live code example. You can execute the example for different values, even can edit and write your examples to test the Java code.



About the author:
A Computer Science and Engineering Graduate(2016-2020) from JSSATE Noida. JAVA is Love. Sincerely Followed Sachin Tendulkar as a child, M S Dhoni as a teenager, and Virat Kohli as an adult.