Java Math abs() Method
The abs() method of Math class returns the absolute value of the argument where the argument can be int, double, float, long.
Syntax public static int abs(int a) public static float abs(float a) public static double abs(double a) public static long(long a) Parameters The argument whose absolute value is to be determined Return ValueThe abs() method returns the absolute value of the argument.
- If the argument passed is positive, it will return positive value.
- If the argument passed is Infinity, it will return positive infinity.
- If the argument passed is NaN, it will return NaN.
public class JavaMathAbsExample1 { public static void main(String[] args) { int x=-109; int y=109; //returns an absolute value for int type System.out.println("Absolute value of "+x +" : "+Math.abs(x)); System.out.println("Absolute value of "+y +" : "+Math.abs(y)); } }Example 2:
public class JavaMathAbsExample2 { public static void main(String[] args) { double val1=1234545465644555553333.78; double val2=-233.3; //returns an absolute value for double type System.out.println("Absolute value of "+val1+" : "+Math.abs(val1)); System.out.println("Absolute value of "+val2+" : "+Math.abs(val2)); System.out.println("Absolute value of Min value : "+Math.abs(Double. MIN_VALUE)); } }Output:
Absolute value of 1.2345454656445554E21 : 1.2345454656445554E21 Absolute value of -233.3 : 233.3 Absolute value of Min value : 4.9E-324Example 3:
public class JavaMathAbsExample3 { public static void main(String[] args) { Float x =82726f; Float y = -287372356f; //returns an absolute value for float type System.out.println("Absolute value of "+x+" : "+Math.abs(x)); System.out.println("Absolute value of "+y+" : "+Math.abs(y)); System.out.println("Absolute value of Min value : "+Math.abs(Float .MIN_VALUE)); System.out.println("Absolute value of 0/0 : "+Math.abs(0f/0f)); } }Output:
Absolute value of 82726.0 : 82726.0 Absolute value of -2.87372352E8 : 2.87372352E8 Absolute value of Min value : 1.4E-45 Absolute value of 0/0 : NaNExample 4:
public class JavaMathAbsExample4 { public static void main(String[] args) { Long x=223l; Long y=-9l; //returns an absolute value for long type System.out.println("Absolute value of "+x+" : "+Math.abs(x)); System.out.println("Absolute value of "+y+" : "+Math.abs(y)); System.out.println("Absolute value of Min value : "+Math.abs(Long. MIN_VALUE)); } }Output:
Absolute value of 223 : 223 Absolute value of -9 : 9 Absolute value of Min value : -9223372036854775808