Find absolute value in Java
Absolute value is the value which is got by neglecting the signs of the existing value. For eg the absolute value of -12 is 12.
abs(double d), abs(float f), abs(int i) and abs(long l) methods of Math class can be used to find absolute of a value in Java.
The class belongs to java.lang package. The methods are static, so it can be called directly using class name without creating object.
abs(double d)
abs(double d) method can be used to get absolute of a double value.
static double abs(double d) method since it is static we can call directly using class name Math. e.g Math.abs(-20.9999999999).
Example
class MathTest{
public static void main(String args[]){
double d=-12.9999999;
double dtoabs=Math.abs(d);
System.out.println("Absolute value of variable d is "+dtoabs);
}
}
Output
Absolute value of variable d is 12.9999999
abs(float f)
abs(float f) method can be used to get absolute of a float value.
static float abs(float f) method since it is static we can call directly using class name Math. e.g Math.abs(-150.6).
Example
class MathTest{
public static void main(String args[]){
float fl=-12.9999;
float ftoabs=Math.abs(f1);
System.out.println("Absolute value of variable f is "+ftoabs);
}
}
Output
Absolute value of variable f is 12.9999
abs(int i)
abs(int i) method can be used to get absolute of a int value.
static int abs(int i) method since it is static we can call directly using class name Math. e.g Math.abs(-2).
Example
class MathTest{
public static void main(String args[]){
int i=-12;
int itoabs=Math.abs(i);
System.out.println("Absolute value of variable i is "+itoabs);
}
}
Output
Absolute value of variable i is 12
abs(long l1)
abs(long l1) method can be used to get absolute of a long value.
static long abs(long l1) method since it is static we can call directly using class name Math. e.g Math.abs(-200000000).
Example
class MathTest{
public static void main(String args[]){
long ll=-20000000000;
int ltoabs=Math.abs(ll);
System.out.println("Absolute value of variable ll is "+ltoabs);
}
}
Output
Absolute value of variable ll is 20000000000