Java Math.abs() method returns an absolute value of the given number. In this tutorial, we will discuss abs() method with examples.
public class JavaExample { public static void main(String args[]) { int i = -10; float f = -5f; System.out.println(Math.abs(i)); System.out.println(Math.abs(f)); } }
Output:
10 5.0
Syntax of abs() Method
Math.abs(-15.5); //returns 15.5
abs() Description
public static int abs(int num): It returns the absolute value of the passed integer value num. There are other variations of this method in Java Math class. These variations are:
public static int abs(int num); //for integers public static long abs(long num); //for long numbers public static float abs(float num); //for float point public static double abs(double num); //for double num
abs() Parameters
It takes a single parameter:
- num: An int, float, long or double value whose absolute values is to be determined.
abs() Return Values
- If the passed argument is a negative number, the positive number is returned.
- If the passed argument is a positive number, same is returned.
- If argument is infinite, positive infinity returned.
- If the argument is NaN (Not a Number) then NaN is retuned.
Example 1: Absolute value of int, long, float and double
public class JavaExample { public static void main(String args[]) { int i = -10; float f = 5f; //already positive, same returned double d = -12.55; long l = 101L; //same returned System.out.println(Math.abs(i)); System.out.println(Math.abs(f)); System.out.println(Math.abs(l)); System.out.println(Math.abs(d)); } }
Output:
Example 2: Absolute value of infinity and NaN
public class JavaExample { public static void main(String args[]) { //number divided by zero infinity System.out.println(Math.abs(5.0/0)); //zero divided by zero is NaN (Not a Number) System.out.println(Math.abs(0.0/0.0)); } }
Output:
Example 3: Absolute value of Integer.MIN_VALUE and Long.MIN_VALUE
public class JavaExample { public static void main(String args[]) { //lowest possible negative int value is returned System.out.println(Math.abs(Integer.MIN_VALUE)); //lowest possible negative long value is returned System.out.println(Math.abs(Long.MIN_VALUE)); } }
Output: