English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Grund教程

Java Flow Control

Java Array

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Object-Oriented (III)

Java AusnahmeBehandlung

Java List

Java Queue (Queue)

Java Map Collection

Java Set Collection

Java Input/Output (I/O)

Java Reader/Writer

Java other topics

Java Math subtractExact() usage and example

Java Math Mathematische Methoden

Java Math's excludeExact() method subtracts the specified number and returns it.

The syntax of the subtractExact() method is:

Math.subtractExact(num1, num2)

Note: subtractExact() is a static method. Therefore, we can use the Math class name to access this method.

excludeExact() parameter

  • num1 / num2 - To return the first and second values whose difference is to be returned

Note: The data types of these two values should be int or long.

excludeExact() return value

  • Returns the difference between two values

Example1: Java Math.subtractExact()

import java.lang.Math;
class Main {
  public static void main(String[] args) {
    //Create an int variable
    int a = 54;
    int b = 30;
    //subtractExact() with integer parameter
    System.out.println(Math.subtractExact(a, b));  // 24
    //Create a long variable
    long c = 72345678l;
    long d = 17654321l;
    //subtractExact() with long parameter
    System.out.println(Math.subtractExact(c, d));  // 54691357
  }
}

In the above example, we used the Math.subtractExact() method with int and long variables to calculate the difference.

Example2: Math.subtractExact() throws an exception

If the result of the difference overflows the data type, the method excludeExact() will throw an exception. That is, the result should be within the range of the specified variable's data type.

import java.lang.Math;
class Main {
  public static void main(String[] args) {
    //Create an int variable.
    //maximum int value
    int a = 2147483647;
    int b = -1;
    //subtractExact() with int parameter
    //Verursacht eine Ausnahme
    System.out.println(Math.subtractExact(a, b));
  }
}

Im obigen Beispiel ist der Wert von a der größte int-Wert und der Wert von b-1Wenn wir a und b verringern

  2147483647 - (-1)
=> 2147483647 + 1
=> 2147483648      //Über den Umfang des int-Typs hinaus

Daher löst die subtractExact() Methode eine Integer-Überlauf-Exception aus.

Empfohlene Tutorials

Java Math Mathematische Methoden