Java Long.sum()方法

原文:https://www.studytonight.com/java-wrapper-class/java-long-sum-method

Java sum()方法是java.lang包的Long类的一部分。此方法返回作为参数传递的值的数值总和(即根据+运算符简单地将作为参数传递的两个数字相加)。

语法:

public static long sum(long a, long b)

参数:

传递的参数包括要返回其相加的两个长值。

返回:

返回作为参数传递的两个长值的总和。

例 1:

这里,为了更好地理解该方法,取一些正数和负数。

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

    }      
}

a 和 b 的和为= 39 a 和 b 的和为= -38

例 2:

这里有一个用户定义的例子,任何使用这段代码的人都可以输入自己选择的值,并获得等效的输出。

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");
        }
    }  
}

输入两个值: 90 -55 之和为= 35 *输入两个值: 90 -534 之和为= -444

实时示例:

在这里,您可以测试实时代码示例。您可以为不同的值执行示例,甚至可以编辑和编写您的示例来测试 Java 代码。