Java Find Absolute value abs()


java.lang.Math class comes with many methods to do simple basic numeric operations. One such one is abs() method which returns always a positive value (knwon as absolute value) of any postive or negative number (int, long, float or double) passed as parameter. Sometimes, it may be required in computing always a positive value eventhough user enters a negative value by mistake.

One advantage of Math class methods is that they are declared as static so that they can be called without the need of object creation.

Following is the Math class signature as defined in java.lang package.

public final class Math extends Object

abs() method in Math class is 4 times overloaded accepting 4 different types of arguments.

  1. int abs(int a): Returns the positive value of the negative integer value passed as parameter.
  2. long abs(long a): Returns the positive value of the negative long value passed as parameter.
  3. float abs(float a): Returns the positive value of the negative float value passed as parameter.
  4. double abs(double a): Returns the positive value of the negative double value passed as parameter.

Observe, the above methods data type of the returned value is the same as parameter.

Example on absolute value abs() using all the above four mehods
public class MathFunctionDemo
{
  public static void main(String args[])
  {
   int a = -25;			//  negative integer value
   long b = -60;		//  negative long value
   float c = -25.5f;		//  negative float value
   double d = -45.6;		//  negative double value

   System.out.println("Absolute (positive) integer value of -25 is " + Math.abs(a));     
   System.out.println("Absolute (positive) long value of -60 is " + Math.abs(b));     
   System.out.println("Absolute (positive) float value of -25.5 is " + Math.abs(c));     
   System.out.println("Absolute (positive) double value of -45.6 is " + Math.abs(d));     
  }
}

Screenshot of the above code when run.

absolute value abs()

Leave a Comment

Your email address will not be published.