×

Java Programs

Java Practice

Java program to demonstrate the Math.subtractExact() method

Java example to demonstrate the Math.subtractExact() method.
Submitted by Nidhi, on May 17, 2022

Problem statement

In this program, we will create an integer number from the user using the Scanner class. Then we will use Math.subtractExact() method. The Math.subtractExact() method returns the subtraction of its arguments, throwing an exception if the result overflows.

Java program to demonstrate the Math.subtractExact() method

The source code to demonstrate the Math.subtractExact() method is given below. The given program is compiled and executed successfully.

// Java program to demonstrate the 
// Math.subtractExact() method

import java.util.*;

public class Main {
  public static void main(String[] args) {
    int num = Integer.MIN_VALUE;

    try {
      System.out.println("Subtraction is: " + Math.subtractExact(num, 0));
      System.out.println("Subtraction is: " + Math.subtractExact(num, 1));
    } catch (Exception e) {
      System.out.println("Exception: " + e);
    }
  }
}

Output

Subtraction is: -2147483648
Exception: java.lang.ArithmeticException: integer overflow

Explanation

In the above program, we imported the "java.util.*" package to use the Scanner class. Here, we created a public class Main that contains a main() method.

The main() method is the entry point for the program. And, created a variable num of integer type and then we used Math.subtractExact() method. It returns the subtraction of its arguments, throwing an exception if the result overflows.

Java Math Class Programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.