StrictMath.negateExact(int): This method is available in java.lang.StrictMath class of Java.
Syntax:
int java.lang.StrictMath.negateExact(int a)
This method takes one argument of type int as its parameter. This method returns the negation of the argument, throwing an exception if the result overflows an int. The overflow only occurs for the minimum value.
Parameters: One parameter is required for this method.
a: the value to negate.
Returns: the result.
Throws:
ArithmeticException - if the result overflows an int.
Approach 1: When no exceptions.
Java
public class StrictMathnegateExactint {public static void main(String[] args) {int a = 1818;System.out.println(StrictMath.negateExact(a));}}
Output:
-1818
Approach 2: ArithmeticException
Java
public class StrictMathnegateExactint {public static void main(String[] args) {int a = Integer.MAX_VALUE + 1;System.out.println(StrictMath.negateExact(a));}}
Output:
Exception in thread "main" java.lang.ArithmeticException: integer overflow at java.base/java.lang.Math.negateExact(Math.java:1044) at java.base/java.lang.StrictMath.negateExact(StrictMath.java:909)
No comments:
Post a Comment