In this tutorial we will go over how do you turn a negative value into a positive value? Simple method is to multiply negative number with Minus One to Convert a Positive Number.
In this tutorial we will go over Math.abs()
function to achieve the same. By converting we will get Absolute value
.
Here is a java program:
Create class CrunchifyConvertNegativeToPositive.java
package crunchify.com.java.tutorials; /** * @author Crunchify.com * In Java how to convert Negative Number to Positive Number? */ public class CrunchifyConvertNegativeToPositive { public static void main(String[] args) { int crunchifyTotal = 20 + 20 + 20 + (-20); // Here output would be 40 crunchifyPrint("Total of 20 + 20 + 20 + 20 + (-20): " + crunchifyTotal); // abs() Returns the absolute value of an int value. If the argument is not negative, the argument is returned. If the argument is negative, the negation of the argument is returned. //Note that if the argument is equal to the value of Integer.MIN_VALUE, the most negative representable int value, the result is that same value, which is negative. // In contrast, the absExact(int) method throws an ArithmeticException for this value. int updatedCrunchifyTotal = 20 + 20 + 20 + Math.abs(-20); // Here output would be 80 crunchifyPrint("After Math.abs() method : " + updatedCrunchifyTotal); } private static void crunchifyPrint(String print) { System.out.println(print); } }
public static int abs(int a)
Returns the absolute value of an int value. If the argument is not negative, the argument is returned. If the argument is negative, the negation of the argument is returned.
Note that if the argument is equal to the value of Integer.MIN_VALUE
, the most negative representable int value, the result is that same value, which is negative. In contrast, the absExact(int)
method throws an ArithmeticException for this value.
Just run above program as Java Application and you should see result like below.
IntelliJ IDEA console output.
/Library/Java/JavaVirtualMachines/jdk-15.jdk/... Total of 20 + 20 + 20 + 20 + (-20): 40 After Math.abs() method : 80 Process finished with exit code 0
Let me know if you face any issue running this program.