Signup/Sign In
LAST UPDATED: NOVEMBER 24, 2020

Java Long sum() Method

Java sum() method is a part of the Long 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 long sum(long a, long b)  

Parameters:

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

Returns:

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

Example 1:

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

import java.lang.Long;

public class StudyTonight
{  
    public static void main(String[] args) 
    {          
        long a = 10L;  
        long b = 29L;  
        long c = -67L;

        System.out.println("The sum of a and b is = " + Long.sum(a, b));  // It will return the sum of a and b
        System.out.println("The sum of a and b is = " + Long.sum(b, c));  // It will return the sum of b and 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);  
			long a = sc.nextLong();  
			long b = sc.nextLong();  
			System.out.println("sum is = " + Long.sum(a, b));  // will return the sum of a and b. 
		}
		catch(Exception e)
		{
			System.out.println("Invalid Input");
		}
	}  
}


Enter the two values :
90 -55
sum is = 35
**************************
Enter the two values :
90 -534
sum is = -444

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.