Java Tutorial Java Advanced Java Resources
Python Java C++ C C# PHP R SQL DS Algo InterviewQ

Java - Math subtractExact() Method

The Java Math subtractExact() method returns difference of its arguments. The method can be overloaded and it can take int and long arguments. It throws an exception, if the result overflows an int or a long.


public static int subtractExact(int x, int y)  
public static long subtractExact(long x, long y)  


x Specify the first value.
y Specify the second value to subtract from first.

Return Value

Returns difference of its arguments.


throws ArithmeticException, if the result overflows an int or a long.


In the example below, subtractExact() method is used to find difference of given numbers.

public class MyClass {
 public static void main(String[] args) {
  int x = 12, y = 17;
  long p = 145, q = 139;
  System.out.println(Math.subtractExact(x, y)); 
  System.out.println(Math.subtractExact(p, q));    

The output of the above code will be:


❮ Java Math Methods