Java Math negateExact() Method

Java Math negateExact() Method

Java Math Class

Here, in the page we will discuss about the math negateExact() Method in java.Java Math class provides several methods to perform several operations on math calculations like max(), min(), sin(), cos(), round(), ceil(), floor(), abs() etc. The java.lang.Math class contains various methods for performing basic numeric operations

Java Math negateExact() Method :

In Java, the Math.negateExact(long a) method is a utility method in the Math class that performs an arithmetic operation to negate a long value and return the result, throwing an exception if the result overflows the range of the long data type.
 
The negateExact() method takes a single parameter, a, which is the long value to be negated. It returns a long value representing the negated value of a.
 
If the result of the negation overflows the range of the long data type, the negateExact() method throws an ArithmeticException.

Syntax  :

public static long negateExact(long a)

Example 1 :  

Run
public class Main {
    public static void main(String[] args) {
        long a = 100;
        long result = Math.negateExact(a);
        System.out.println(result); // prints -100
    }
}

Output :

-100

Example 2:  

Run
public class Main {
    public static void main(String[] args) {
        long a = Long.MIN_VALUE;
        try {
            long result = Math.negateExact(a);
            System.out.println(result);
        } catch (ArithmeticException e) {
            System.out.println("Overflow occurred");
        }
    }
}

Output :

Overflow occurred

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription