In Java programming, manipulating numeric values is a fundamental aspect, and sometimes, you might find yourself needing to convert a positive integer to its negative counterpart. This conversion is a straightforward process, but understanding how to do it correctly is essential for various applications, such as mathematical computations, data transformations, or algorithm implementations. In this blog post, we'll explore how to convert a positive integer to a negative integer in Java.
1. Simple Negation Using the Unary Minus Operator
The most direct way to convert a positive integer to a negative is by using the unary minus (-) operator. This operator changes the sign of the number.
Example:
public class PositiveToNegative {
public static void main(String[] args) {
int positiveNumber = 50;
int negativeNumber = -positiveNumber;
System.out.println("Positive Number: " + positiveNumber);
System.out.println("Converted Negative Number: " + negativeNumber);
}
}
Output:
Positive Number: 50 Converted Negative Number: -50In this example, the unary minus operator is used to convert the positive number 50 to -50.
2. Using Math.negateExact()
Example:
public class PositiveToNegative {
public static void main(String[] args) {
int positiveNumber = 50;
int negativeNumber = Math.negateExact(positiveNumber);
System.out.println("Positive Number: " + positiveNumber);
System.out.println("Converted Negative Number: " + negativeNumber);
}
}
Output:
Positive Number: 50 Converted Negative Number: -50Using Math.negateExact() not only converts the number but also throws an ArithmeticException if the result overflows an int.
Handling Edge Cases
Example of Integer Overflow:
public class PositiveToNegative {
public static void main(String[] args) {
int positiveNumber = Integer.MAX_VALUE;
int negativeNumber = -positiveNumber;
System.out.println("Positive Number: " + positiveNumber);
System.out.println("Converted Negative Number: " + negativeNumber);
}
}
Output:
Positive Number: 2147483647 Converted Negative Number: -2147483647In this case, negating Integer.MAX_VALUE doesn't result in overflow, but if you were to negate Integer.MIN_VALUE, it would.
Comments
Post a Comment
Leave Comment