Java Integer sum()方法

来源:这里教程网 时间:2026-02-17 20:51:19 作者:

Java Integer sum()方法

java.lang.Integer.sum()是java中的一个内置方法,用于返回其参数的总和。该方法按照+运算符将两个整数相加。

语法:

public static int sum(int a, int b)

参数。该方法接受两个参数,这两个参数将被相互添加:

a : 第一个整数值。

b : 第二个整数值。

返回值。该方法返回其参数之和。

异常。当结果溢出一个int时,该方法会抛出一个ArithmeticException。

例子

Input: a = 170, b = 455Output: 625Input: a = 45, b = 45Output: 90

下面的程序说明了Java.lang.Integer.sum()方法:

程序1: 对于一个正数。

// Java program to illustrate the// Java.lang.Integer.sum() methodimport java.lang.*;  public class Geeks {      public static void main(String[] args)    {        int a = 62;        int b = 18;        // It will return the sum of two arguments.        System.out.println("The sum is =" + Integer.sum(a, b));    }}

输出。

The sum is =80

方案2: 下面的方案说明了这个例外。

// Java program to illustrate the// Java.lang.Integer.sum() methodimport java.lang.*;  public class Geeks {      public static void main(String[] args)    {        // When very large integer is taken        int a = 92374612162;         int b = 181;        // It will return the sum of two arguments.        System.out.println("The sum is =" + Integer.sum(a, b));    }}

输出。

prog.java:8: error: integer number too large: 92374612162       int a = 92374612162;               ^1 error

相关推荐