The absolute value of a real number is its positive value irrespective of its sign. In mathematics, absolute value of x is denoted by |x|. For instance, if we’ve -10 the absolute value will be 10. In java, abs()
is used to transform a real number into its absolute value.Â

Syntax
Here, we have general syntax for abs()
function.
public static dataType abs(dataType value)
Java programming language supports the following variants:
static double abs(double a)
static float abs(float a)
static int abs(int a)
static long abs(long a)
Parameters
It takes a number whose absolute value will be evaluated. It can be int
, float
, double
, or long
.
Return value
It returns the absolute value of the argument number. It can be int
, float
, double
, or long
.
Explanation
In this coding example, we’re going to elaborate on how abs()
function behave upon different argument types.
class AlgoIdeas {
public static void main( String args[] ) {
/* Converting integer values into absolute values */
int x1 = 456;
int y1 = -845;
System.out.printf( "Absolute Value of x1: %d \n", Math.abs(x1) );
System.out.printf( "Absolute Value of y1: %d \n", Math.abs(y1) );
/* Converting double values into absolute values */
double x3 = 456;
double y3 = -279;
System.out.printf( "Absolute Value of x3: %f \n", Math.abs(x3) );
System.out.printf( "Absolute Value of y3: %f \n", Math.abs(y3) );
/* Converting float values into absolute values */
float x2 = 12.3f;
float y2 = -13.4f;
System.out.printf( "Absolute Value of x2: %f \n", Math.abs(x2) );
System.out.printf( "Absolute Value of y2: %f \n", Math.abs(y2) );
/* Converting long type values into absolute values */
long x4 = 345L;
long y4 = -567L;
System.out.printf( "Absolute Value of x4: %d \n", Math.abs(x4) );
System.out.printf( "Absolute Value of y4: %d \n", Math.abs(y4) );
}
}
- Line#4-8: Defining two
integer
values x1, and y1. Then invokingMath.abs()
method to calculate the absolute value. It will return an absolute value of the same type as argument values. - Line#10-14: Defining two
double
values x2, and y2. Then invokingMath.abs()
method to calculate the absolute value. It will return an absolute value of the same type as argument values. - Line#16-20: Defining two
floating point
values x3, and y3. Then invokingMath.abs()
method to calculate the absolute value. It will return an absolute value of the same type as argument values. - Line#22-26: Defining two
long
values x4, and y4. Then invokingMath.abs()
method to calculate the absolute value. It will return an absolute value of the same type as argument values.
Output
