Curriculum
Course: Java Basic
Login

Curriculum

Java Basic

Java Home

0/1

Java Introduction

0/1

Java Get Started

0/1

Java Syntax

0/1

Java Comments

0/1

Java Type Casting

0/1

Java Operators

0/1

Java Booleans

0/1

Java Switch

0/1

Java Break / Continue

0/1

Java Errors and Exception

0/1
Text lesson

negateExact()

Example

Alter the signs of various numbers.

System.out.println(Math.negateExact(15));
System.out.println(Math.negateExact(-32));
System.out.println(Math.negateExact(7));
System.out.println(Math.negateExact(-25));

Definition and Usage

The negateExact() method in Java returns an integer with the same absolute value but the opposite sign of another integer, while handling overflow situations by throwing an exception. This safeguards against inaccuracies that may arise due to overflow.

An overflow typically arises when the integer reaches the minimum value, such as Integer.MIN_VALUE or Long.MIN_VALUE, representing the largest negative integer, as it lacks a positive equivalent.

Syntax

One of the following:

public static int negateExact(int x)
 public static long negateExact(long x)

Parameter Values

Parameter

Description

X

Please provide an integer to negate.

Technical Details

Returns:

An int or long value representing an integer with an equivalent magnitude but opposite sign to another integer.

Throws:

An ArithmeticException is thrown if the negation operation results in an overflow.

Java Version:

1.8+