Java.lang.StrictMath 类

java.lang.StrictMath.subtractExact() 方法返回其参数的差值。如果结果溢出 int,它将引发异常。

语法

public static int subtractExact(int x, int y)    
  • 1

参数

x 指定第一个值。
y 指定要从第一个值中减去的第二个值。

返回值

返回其参数的差异。

异常

抛出ArithmeticException,如果结果溢出 int。

示例:

在下面的示例中,使用了 subtractExact() 方法查找给定数字的差异。

import java.lang.*;

public class MyClass {
 public static void main(String[] args) {
  int x = 12;
  int y = 17;

  int p = 145;
  int q = 139;
  
  System.out.println(StrictMath.subtractExact(x, y)); 
  System.out.println(StrictMath.subtractExact(p, q));    
 }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

上述代码的输出将是:

-5
6
  • 1
  • 2