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

Java Basic Tutorial

Java Flow Control

Java Array

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Object-Oriented (III)

Java Exception Handling

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 Mathematical Methods

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() parameters

  • 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.

The return value of excludeExact()

  • 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;
    //The subtractExact() with integer parameter
    System.out.println(Math.subtractExact(a, b));  // 24
    //Create a long variable
    long c = 72345678l;
    long d = 17654321l;
    //The 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 excludeExact() method 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;
    //The subtractExact() with int parameter
    //throws an exception
    System.out.println(Math.subtractExact(a, b));
  }
}

In the above example, the value of a is the maximum int value and the value of b is-1When we subtract a and b,

  2147483647 - (-1)
=> 2147483647 + 1
=> 2147483648      //Out of the range of int type

Therefore, the subtractExact() method triggers an integer overflow exception.

Recommended Tutorials

Java Math Mathematical Methods