Java Integer.sum()方法

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

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

语法:

public static int sum(int a, int b)

参数:

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

返回:

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

例 1:

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

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

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

输入两个值: 67 54 之和为= 121

                                                          • T4】输入两个值: 55 -33 之和为= 22
                                                                              • *输入两个值: 0x56 0x767 无效输入

实时示例:

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